On 10 August 2010 17:09, Fritz Anderson <[email protected]> wrote: > I have two tables, media and tour_locations, related through a join > table. It's not a pure join, because I need a sequence number on the > relationship, so the join also has an id. When I access > "aMedium.tour_locations", the reported id's for the TourLocation's are > the id's from the join table, not the real id of the tour_locations row. > The same for "aTourLocation.media". In the sqlite3 console, the keys and > ids are all correct.
[snip] > class TourLocation: > ====== > class TourLocation < ActiveRecord::Base > has_and_belongs_to_many :media, > :join_table => "media_tour_locations", > :readonly => false > > class Medium: > ====== > class Medium < ActiveRecord::Base > has_and_belongs_to_many :tour_locations, > :join_table => "media_tour_locations", > :readonly => false > > Schema: > ====== > create_table "media", :force => true do |t| > t.string "url", :null => false > t.string "title", :default => "" > t.text "description", :default => "" > t.string "media_type", :default => "image", :null => false > end > > create_table "media_tour_locations", :force => true do |t| > t.integer "medium_sequence" > t.integer "medium_id" > t.integer "tour_location_id" > end > > create_table "tour_locations", :force => true do |t| > t.text "locDescription", :default => "Enter description", > :null => false > end The has_and_belongs_to_many assumes that the join table doesn't have a column called 'id' -- you'll see that the SQL it generates just SELECTs an 'id' column, so it's (erroneously) picking up the one from the join table in your situation. If your join table is really a fully-fledged model of its own, then you need to bring it into the association explicitly, and use the :through option to connect media and tour_locations: class Medium < ActiveRecord::Base has_many :media_tour_locations has_many :tour_locations, :through => :media_tour_locations end class MediaTourLocation < ActiveRecord::Base belongs_to :medium belongs_to :tour_location end class TourLocation < ActiveRecord::Base has_many :media_tour_locations has_many :media, :through => :media_tour_locations end Chris -- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

