假设我正在创建一个博客网站,用户可以在其中发帖并关注其他用户。我希望用户和用户关注的所有人都有一个ActiveRecord关系。我可以将它作为ruby方法来实现,我在下面的posts_by_me_and_people_i_am_following
类中将其称为User
。有没有办法用纯粹的ActiveRecord制作它?
class User
has_many :posts
has_many :follows
has_many :followed_users, through: follows, source: :target_user
has_many :posts_by_followed_users, through: :followed_users, source: :posts
# I want this to be an ActiveRecord::Relation so that I can filter or order it
def posts_by_me_and_people_i_am_following
posts.to_a + posts_by_followed_users.to_a
end
end
class Post
belongs_to: :user
end
class Follow
belongs_to :target_user, class_name: "User"
belongs_to :source_user, class_name: "User"
end
答案 0 :(得分:1)
听起来像是ARel的工作。
def posts_by_me_and_people_i_am_following
t = Post.arel_table
results=Post.where(
t[:user_id].eq(self.id).
or(t[:user_id].in(self.followed_user_ids))
)
end