2012-07-24 33 views
1

我不知道爲什麼我找不到什麼看起來像是一個非常基本的問題。假設我有類似Rails:在HABTM加入模型中分配額外的列

class Category < ActiveRecord::Base 
    has_many :categorizations 
    has_many :items, :through => :categorizations 
end 

class Item < ActiveRecord::Base 
    has_many :categorizations 
    has_many :categories, :through => :categorizations 
end 

class Categorization < ActiveRecord::Base 
    attr_accessible :some_field 
    belongs_to :category 
    belongs_to :item 
end  

和相關的遷移。那麼可以做

item1=Item.new() 
item2=Item.new() 
foo=Category.new() 
foo.items=[ item1, item2 ] 

,對吧?那麼,如何獲得將foo鏈接到item1和item2的Categorizations,以便設置some_field的值?

+0

您需要將id放入Categorization模型,但任何ActiveRecord對象上的id只有在將其保存到數據庫後纔會出現。 – 2012-07-25 05:36:58

回答

3

如果你想添加額外的東西,你不能使用快速通道。我現在不能測試,但這樣的事情應該工作:

item1 = Item.new 
item2 = Item.new 

foo = Category.new 
foo.categorizations.build(:some_field=>'ABC', :item=>item1) 
foo.categorizations.build(:some_field=>'XYZ', :item=>item2) 

UPDATE:

另外:如果你需要從Categorization顯示額外的數據不能使用@category.items

<h1><%= @category.name %></h1> 

<% @category.categorizations.each do |categorization| %> 
    <h2><%= categorization.item.name %></h2> 

    <p>My extra information: <%= categorization.some_field %></p> 
<% end %> 
+0

謝謝!這正是我想要找到的。 – cbmanica 2012-07-25 16:54:51

相關問題