我无法生成嵌套模型表单。

这里是我的型号:

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
.

在锻炼控制器中,这是我对新动作的东西:

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 %>
.

我做错了什么?

有帮助吗?

解决方案

它在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
.

只需将使用要创建的分数所需的相关字段切换生成字段。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top