我在生成嵌套模型表单时遇到了麻烦。
以下是我的模特:
class Workout < ActiveRecord::Base
has_many :scores
has_many :users, :through => :scores
accepts_nested_attributes_for :scores
end
class Score < ActiveRecord::Base
belongs_to :user
belongs_to :workout
end
class User < ActiveRecord::Base
has_many :scores
has_many :workout, :through => :scores
end
在Workout控制器中,这是我对新动作的所有内容:
def new
@workout = Workout.new
3.times { @workout.scores.build }
respond_to do |format|
format.html # new.html.erb
format.json { render json: @wod }
end
end
然而,在表单中,当我尝试fields_for时,我什么都没得到:
<% f.fields_for :scores do |builder| %>
<p>
<%= builder.label :score %><br />
<%= builder.text_field :score %>
</p>
<% end %>
我做错了什么?
答案 0 :(得分:6)
事实证明,在Rails 3中,我需要使用&lt;%= fields_for ...%&gt;而不是&lt;%fields_for ...%&gt;。
答案 1 :(得分:0)
尝试将以下内容添加到Workout
模型中:
attr_accessible :scores_attributes
accepts_nested_attributes_for :scores
如果你想确保得分没有建成,除非它有效,并且可以通过关系销毁,你可以扩展到:
attr_accessible :scores_attributes
accepts_nested_attributes_for :scores, reject_if: proc { |a| a[:field].blank? }, allow_destroy: true
validates_associated :scores
只需使用创建分数所需的相关字段切换:field
即可。