我有兩個模型:用戶,文章如何在Rails中定義多個has_and_belongs_to_many?
用戶可以喜歡或不喜歡很多文章,並且文章可以被許多用戶喜歡或不喜歡。所以我需要在它們之間建立一個多對多的關係。
在軌道,我想我需要使用has_and_belongs_to_many ..
我覺得代碼的結構如下圖所示:
class User
has_and_belongs_to_many :liked_articles
has_and_belongs_to_many :disliked_articles
end
class Article
has_and_belongs_to_many :liking_users
has_and_belongs_to_many :disliking_users
end
當然,上面的代碼不起作用。
但我不知道什麼是正確的代碼。誰能幫我?
更新時間:
我想出了這樣的代碼:
class User
has_and_belongs_to_many :liked_articles, :class_name => 'Article', :join_table => 'articles_users_like', :uniq => true
has_and_belongs_to_many :disliked_articles, :class_name => 'Article', :join_table => 'articles_users_dislike', :uniq => true
end
class Article
has_and_belongs_to_many :liking_users, :class_name => 'User', :join_table => 'articles_users_like', :uniq => true
has_and_belongs_to_many :disliking_users, :class_name => 'User', :join_table => 'articles_users_dislike', :uniq => true
end
我認爲它會工作。
但正如Peter Sobot和Jon McIntosh所說,現在has_many,:through是更優選的。你能告訴我爲什麼嗎? 後者在邏輯上比has_and_belongs_to更清晰?
你的回答很清楚。但我仍然有一個問題。我已更新問題,請檢查〜:) – HanXu 2012-03-30 04:26:29
編輯我的回覆 – 2012-03-30 06:08:49
太棒了!謝謝! – HanXu 2012-03-30 09:39:35