I have two models, User and Discussion
User model
has_and_belongs_to_many :subscribed_discussions, :class_name => 'Discussion', :join_table => 'discussions_subscriptions'
has_many :discussions
Discussion model
has_and_belongs_to_many :subscribed_users, :class_name => 'User', :join_table => 'discussions_subscriptions'
belongs_to :user
When I access discussions from a user u.subscribed_discussions[0].user_id, I get a completely different value of user than when I access the user directly from Discussion.find
system :029 > u.subscribed_discussions.first == Discussion.find(10)
=> true
system :030 > Discussion.find(10)
=> #<Discussion id: 10, title: "MBA", content: "What do you think about management education, speci...", user_id: 7, created_at: "2011-01-24 21:44:22", updated_at: "2011-01-24 21:44:22", group_id: nil, profile_id: 8>
system :031 > u.subscribed_discussions.first
=> #<Discussion id: 10, title: "MBA", content: "What do you think about management education, speci...", user_id: 1, created_at: "2011-01-24 21:44:22", updated_at: "2011-01-24 21:44:22", group_id: nil, profile_id: 8>
system :032 > u.id
=> 1
system :034 > Discussion.find(10).user_id
=> 7
u is a user who has subscribed to the discussion with id=10. When I access the discussion through the subscribed_discussions relationship, and access its user, I get u back, instead of the creator of that discussion.
I confirmed this on IRC that this is a bug in HABTM relationships in Rails 3, if one of the table and the join table both have a column of the same name.