I'm having an issue with the data returning from a self-referential many-to-many relationship with an attribute in the join table that's being used to limit the query. I'll explain what I'm doing below which will then bring you to the problem concerning the records I'm getting back from the relationship.
MIGRATIONS (the two tables involved in the problem)
Note that in contained_gear_items there are three items related to gic[1] and list_id 1 and two other items related to gic[1] but belong to list_id 2 so I would think I wouldn't see them (considering I have 'contained_gear_items.list_id" => 1' in the conditions - see below). When looking at .contained_items the list_id = 1 constraint seems to have been missed. But if I go directly into the contained_gear_items join model I see only the three items, as I should. Any help would be much appreciated.
so, data wise, contained_gear_item goes like this:
id gear_item_id contained_gear_item_id list_id 1 4 9 2 2 4 10 2 5 4 5 1 6 4 6 1 7 4 7 1
#011_create_contained_gear_items.rb (migration) class CreateContainedGearItems < ActiveRecord::Migration def self.up create_table :contained_gear_items do |t| t.integer "gear_item_id", :null => false t.integer "contained_gear_item_id", :null => false t.integer "list_id", :null => false t.integer "position" t.timestamps end end
## 001_create_gear_items.rb (migration) class CreateGearItems < ActiveRecord::Migration def self.up create_table :gear_items do |t| t.string "title", :limit => 100, :null => false t.boolean "is_container", :default => false t.timestamps end end
MODELS
## gear_item.rb (model) class GearItem < ActiveRecord::Base has_many :contained_gear_items has_many :contained_items, :through => :contained_gear_items
## contained_gear_item.rb (model) class ContainedGearItem < ActiveRecord::Base belongs_to :gear_item belongs_to :contained_item, :class_name => 'GearItem', :foreign_key => 'contained_gear_item_id'
IN THE SCRIPT/CONSOLE
gic = GearItem.find(
:all, :include => "contained_gear_items", :conditions => {"contained_gear_items.list_id" => 1, :is_container => true}, :order => "contained_gear_items.position")
puts gic[1].contained_items
#<GearItem:0x3efeb80> #<GearItem:0x3efeb30> #<GearItem:0x3efeae0> #<GearItem:0x3efea90> #<GearItem:0x3efea40>
puts gic[1].contained_gear_items
#<ContainedGearItem:0x3f2c56c> #<ContainedGearItem:0x3f29a4c> #<ContainedGearItem:0x3f27328>
Thanks for any help you can provide...
Cheers