如何在与模型绑定的表单助手中引用相关模型的字段?

时间:2011-11-19 04:14:16

标签: ruby-on-rails ruby

在这里完成Rails的初学者:

在Rails中:

我有一个模型帖子,里面有很多标签。在创建新帖子时,我希望用户能够创建最多5个与帖子绑定的标签。

我将表单设置为创建一个像这样的新帖子:

<%= form_for(@post) do |f| %>
   <div class="field">
      <%= f.label :name %><br/>
      <%= f.text_field :name %>
   </div>
   ... Some more of these
   <div class="field">   <!-- I want this to refer to the name attribute of a Tag model-->
      <%= f.label :tag_name %><br />
      <%= f.text_field :tag_name %>
   </div>
<% end %>

显然,这不起作用,因为Post类没有tag_name属性。这样做的正确方法是什么?

假设Tag是一个聚合表,其中包含以下字段:

id: primary key
post_id: foreign key to Post's primary key
name: name of the tag

2 个答案:

答案 0 :(得分:2)

尝试使用accepts_nested_attributes_for

class Post < ActiveRecord::Base
  has_many :tags
  accepts_nested_attributes_for :tags
end

class Address < ActiveRecord::Base
  attr_accessible :post_id
  belongs_to :post
end

在表单上,​​以及Post的属性,使用:

<% f.fields_for :tag, @post.address do |builder| %>
   <p>
     <%= builder.text_field :post_id %>
   <p>
<% end %>

这样的事情。祝你好运。

答案 1 :(得分:1)

查看此railscast

基本上,您需要accepts_nested_attributes_for然后fields_for

相关问题