2013-01-22 27 views
0

進出口尋找建立以下數據結構的形式,正確的方法:嵌套屬性不負擔我訪問相關的模型數據

class Profile < ActiveRecord::Base 
    attr_accessible :name 
    has_many :weights 
    accepts_nested_attributes_for :weights 
end 

class Tag < ActiveRecord::Base 
    attr_accessible :name 
    has_many :weights 
end 

class Weight < ActiveRecord::Base 
    attr_accessible :weight, :profile_id, :tag_id 
    belongs_to :profile 
    belongs_to :tag 
end 

在編輯個人資料表格我想拉一切權重並允許用戶更新它們。我已經能夠使用嵌套屬性要做到這一點,像這樣:

<%= form_for [:admin, @profile] do |f| %> 
    <%= f.error_messages %> 
    <p> 
    <%= f.label :name %> 
    <%= f.text_field :name %> 
    </p> 
    <div class='weights'> 
    <%= f.fields_for :weights do |ff| %> 
     <%= ff.label :weight %> 
     <%= ff.text_field :weight %> 
    <% end %> 
    </div> 

    <%= f.submit %> 
<% end %> 

的事情是,其實我是想在各權重排以及相關TAG_ID的標題拉(讓人們知道它的重量的標籤他們正在改變)。我沒有看到一種方法來提取這些信息,我應該在寫這個表單之前進行某種連接嗎?這是一個愚蠢的做法嗎?

謝謝大家

-Neil

回答

0

您應該能夠通過ff.object和直掛ff.object.tag.title的重量來獲得。你試過這個嗎?

+0

我不知道對象的方法。謝謝! – Neil

+0

這偉大的工作,但現在當我創建一個新的「個人資料」我需要建立對每個標記,像這樣 高清新 配置= Profile.new 的標籤的「權重」的條目= Tag.all tags.each do | tag | profile.weights.build(:tag_id => tag.id,:weight => 0) end end 這將顯示錶單中的所有字段,但是當我提交時,tag_id對於每個權重條目。 @Swards有什麼想法? – Neil

+0

創建操作將收到參數,我懷疑tag_id不在重量屬性中。您可以添加一個隱藏字段來提交標籤ID。 – Swards