我有一個籃球應用程序,其中一個名單有很多玩家,而一個玩家可以在多個名單上(多到多的原因是一個Player-名冊檔案)Rails 3.1+嵌套表單問題:無法批量分配受保護的屬性
Roster.rb
class Roster < ActiveRecord::Base
belongs_to :team
has_many :rosterizes
has_many :players, :through => :rosterizes
accepts_nested_attributes_for :players
attr_accessible :jersey_number, :team_id, :class_year, :players
end
Rosterizes.rb(命名不佳,我知道...)
class Rosterize < ActiveRecord::Base
belongs_to :player
belongs_to :roster
attr_accessible :player_id, :roster_id
end
Player.rb
class Player < ActiveRecord::Base
has_many :rosterizes
has_many :rosters, :through => :rosterizes
validates_presence_of :first_name, :last_name
attr_accessible :first_name, :last_name, :active
end
觀
<div class="well">
<h2>New Player</h2>
<%= simple_form_for @roster, :url =>player_added_team_path, :html => { :class => 'form-horizontal' } do |f| %>
<%= f.simple_fields_for @new_player do |x| %>
<%= x.input :first_name %>
<%= x.input :last_name %>
<%end%>
<%=f.input :class_year %>
<%=f.input :jersey_number %>
<%=f.input :team_id, :as => :hidden, :input_html => {:value => params[:id]}%>
<div class="well">
<%= f.button :submit, :class => 'btn-primary icon-plus-sign btn-success', :value => "Add To Team" %>
</div>
<%end%>
</div>
我發送到控制器PARAMATERS:
"roster"=>{"player"=>{"first_name"=>"first name", "last_name"=>"last name"}, "class_year"=>"freshman", "jersey_number"=>"23", "team_id"=>"1"}, "commit"=>"Add To Team", "id"=>"1"}
控制器,它處理保存:
def player_added
@team = Team.find(params[:id])
#where the issue is happening
@roster = @team.rosters.build(params[:roster])
@roster.save
...
end
我身邊有使用參數,但使用工作,我想了解我在做什麼錯在這裏爲今後/學習的目的,爲什麼它給我:不能質量 - 指定保護屬性
我周圍的工作(有點哈克):
def player_added
@team = Team.find(params[:id])
@roster = @team.rosters.build(:class_year => params[:roster][:class_year], :jersey_number => params[:roster][:jersey_number])
@new_player = @roster.players.build(:first_name => params[:roster][:player][:first_name], :last_name => params[:roster][:player][:last_name])
@roster.save
@new_player.save
...
end
我使用Simple_Form 2.0 ...
我知道這是很多的信息,但是提前謝謝你!
SOLUTION
只是櫃面其他人是否有相同的我是相同/相似的問題...
我=>https://github.com/ryanb/nested_form
安裝此插件所以這是我的變化製作:
名冊。RB
class Roster < ActiveRecord::Base
belongs_to :team
has_many :rosterizes
has_many :players, :through => :rosterizes
accepts_nested_attributes_for :players
attr_accessible :jersey_number, :class_year, :players, :player_attributes
end
我也作了變化視圖,以:
<%= simple_nested_form_for @roster, :url =>player_added_team_path, :html => { :class => 'form-horizontal' } do |f| %>
<%= f.simple_fields_for :players, @roster.players.build do |x| %>
# nested form
...
<%end%>
# form
...
<%end%>
控制器保存 DEF player_added
@team = Team.find(params[:id])
@roster = @team.rosters.build(params[:roster])
@roster.save
...
端
這是一種痛苦在對接fo讓我明白,希望這會減少你尋找答案/學習nested_forms的時間!
'accep_nested_attributes_for:players' – DGM 2012-04-20 03:57:34