加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 获取fields_for以使用has_many关系

发布时间:2020-12-17 03:21:33 所属栏目:百科 来源:网络整理
导读:我在生成嵌套模型表单时遇到问题. 这是我的模特: class Workout ActiveRecord::Base has_many :scores has_many :users,:through = :scores accepts_nested_attributes_for :scoresendclass Score ActiveRecord::Base belongs_to :user belongs_to :workout
我在生成嵌套模型表单时遇到问题.

这是我的模特:

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

我究竟做错了什么?

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读