【问题标题】:Getting fields_for to work with has_many relationship让 fields_for 使用 has_many 关系
【发布时间】:2012-02-27 01:29:43
【问题描述】:

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

这是我的模型:

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

我做错了什么?

【问题讨论】:

  • 什么是Wod,为什么要在锻炼控制器中创建它?

标签: ruby-on-rails ruby ruby-on-rails-3.2


【解决方案1】:

事实证明,在 Rails 3 中,我需要使用 而不是 。

【讨论】:

    【解决方案2】:

    尝试将以下内容添加到您的 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 切换为创建分数所需的相关字段。

    【讨论】:

    • 真傻,问题是使用 而不是
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多