一对多属性嵌套属性

时间:2017-10-04 02:02:00

标签: ruby-on-rails ruby-on-rails-5

我有一个表格可以为联盟创造一个联盟和10支球队。我无法设置后端来执行此操作。

现在我打击了我的后端:

{{1}}

1 个答案:

答案 0 :(得分:2)

看看是否有效。

class League < ActiveRecord::Base
    has_many :teams
    accepts_nested_attributes_for :teams
end

LeagueController:league_params 中,将嵌套属性列入白名单。请注意, teams_attributes 是白名单而不是团队

def league_params 
     params.require(:league).permit( :id, :name, teams_attributes: [ :id, :name ] )
end

确保以下param结构符合代码。请注意从 团队 更改为 teams_attributes

{"league" =>{"name"=>"League Name", "teams_attributes"=>[{"name"=>"Team 1"}, {"name"=>"Team 2"}, {"name"=>"Team 3"}]}}

代码未经过测试,因此可能需要进行调整。

相关问题