让fields_for使用has_many关系

我在生成嵌套模型表单时遇到问题。

这是我的模特:

class Workout  :scores accepts_nested_attributes_for :scores end class Score < ActiveRecord::Base belongs_to :user belongs_to :workout end class User  :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时,我什么都没得到:

  


我究竟做错了什么?

事实certificate,在Rails 3中,我需要使用<%= fields_for ...%>而不是<%fields_for ...%>。

尝试将以下内容添加到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其中包含创建分数所需的相关字段。