2012-07-24 45 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