我有一个篮球的应用程序,其中名册有很多球员,而能够向玩家在多个名册。(原因很多一对多的是一个球员,名册存档)
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 ...
我知道这是一个大量的信息,但感谢你提前!
解
只是柜面其他人是否有相同的我是相同/相似的问题...
我=>安装这个插件https://github.com/ryanb/nested_form
所以这就是我所做的更改:
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, :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%>
控制器保存高清player_added
@team = Team.find(params[:id])
@roster = @team.rosters.build(params[:roster])
@roster.save
...
结束
这是在屁股上,我听不懂,希望这将削减下来的时间,以任何你寻找答案/学习nested_forms痛!