Rails:在HABTM连接模型中分配额外的列

时间:2012-07-24 21:33:41

标签: ruby-on-rails ruby

我不知道为什么我找不到任何似乎是一个非常基本的问题。说我有像

这样的东西
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的分类,以便设置值:some_field?

1 个答案:

答案 0 :(得分: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)

<强>更新

另外:如果您需要显示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 %>
相关问题