让 fields_for 使用 has_many 关系 [英] Getting fields_for to work with has_many relationship

查看:40
本文介绍了让 fields_for 使用 has_many 关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm having trouble generating a nested model form.

这是我的模型:

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

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

In the Workout controller, here's what I have for the new action:

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 时,我什么也没得到:

However, in the form, when I try fields_for, I don't get anything:

<% f.fields_for :scores do |builder| %>
    <p>
        <%= builder.label :score %><br />
        <%= builder.text_field :score %>
    </p>
<% end %>

我做错了什么?

推荐答案

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

It turns out in Rails 3, I need to use <%= fields_for ... %> instead of <% fields_for ... %>.

这篇关于让 fields_for 使用 has_many 关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆