开发者

Incorrect object returned from a has_and_belongs_to_many relationship

开发者 https://www.devze.com 2023-02-14 10:58 出处:网络
I have two models, User and Discussion User model has_and_belongs_to_many :subscribed_discussions, :class_name => \'Discussion\', :join_table => \'discussions_subscriptions\'

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开发者_JS百科 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'm assuming your Discussion model belongs_to :user, which means the user_id field on the discussion model will be that user, it's unrelated to the has_and_belongs_to_many :subscribed_users association.

Can you post your models and schema.rb? It'll make it easier to understand what your model is doing.

Also, I suggest moving away from HABTM and using has_many :through instead, it'll give you a richer model.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号