我建立一個小的Twitter微博式的服務,用戶可以跟隨其他用戶,並得到他們的消息的飼料多個連接在軌使用ActiveRecord
我有以下型號:
class Follow < ActiveRecord::Base
belongs_to :follower, :class_name => "User"
belongs_to :followee, :class_name => "User"
end
class User < ActiveRecord::Base
has_many :follows, :foreign_key => 'follower_id',
:class_name => 'Follow'
has_many :followers, :through => :follows
has_many :followed, :foreign_key => 'followee_id',
:class_name => 'Follow'
has_many :followees, :through => :followed
has_many :messages
end
class Message < ActiveRecord::Base
belongs_to :user
end
要獲取當前用戶的飼料,我想執行下面的SQL查詢:
SELECT * FROM follows JOIN users JOIN messages WHERE follows.follower_id = current_user.id AND follows.followee_id = users.id AND users.id = messages.user_id;
什麼是這樣做的正確的ActiveRecord的方式?
has_and_belongs_to_many:followed_messages,:foreign_key => 'follower_id',:CLASS_NAME => '消息',:association_foreign_key => 'followed_id' 產生可以按如下方式執行指定的SQL查詢SQL: SELECT * FROM消息INNER JOIN跟在ON messages.id =後面。followee_id WHERE(follows.follower_id =) ,但我需要它是 messages.user_id = follows.followee_id 有沒有辦法做到這一點? –
Shalmanese
2009-05-10 09:10:31