Reputation: 3854
I don't know why I can't find anything on what seems like a pretty elementary question. Say I have something like
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
and the relevant migrations. Then one can do
item1=Item.new()
item2=Item.new()
foo=Category.new()
foo.items=[ item1, item2 ]
, right? How, then, does one get at the Categorizations that link foo to item1 and item2 in order to set the value of :some_field?
Upvotes: 1
Views: 692
Reputation: 4176
If you want to add extra stuff you can't use the fast track. I can't test it right now, but something like this should work:
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:
Also: If you need to display the extra data from Categorization
you can't use @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 %>
Upvotes: 3