2011-11-19 73 views
2

完整的初學者到Rails的位置:如何在與模型綁定的表單助手中引用相關模型的字段?

在Rails:

我有一個模型後,其中的hasMany標籤。創建新帖子時,我希望用戶能夠創建最多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 %> 

顯然,這不起作用,因爲郵政類沒有TAG_NAME屬性。什麼是正確的方法來做到這一點?

假設標籤是具有以下字段的彙總表:

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

你看過使用nested_attributes_for嗎?這可能會讓你走向正確的道路。 –

回答

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 

在您的形式,與郵政,使用屬性一起:

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

類似的東西。祝好運編碼。

相關問題