gpt4 book ai didi

ruby-on-rails - has_many 上的自定义范围,:through association (Rails 4)

转载 作者:行者123 更新时间:2023-12-04 02:07:35 25 4
gpt4 key购买 nike

语境 :
在我的设置中,用户通过 CommunityUser 拥有许多社区,而社区通过 CommunityPost 拥有许多帖子。如果紧随其后,则该用户通过社区拥有许多帖子。
用户名

has_many :community_users
has_many :communities, through: :community_users
has_many :posts, through: :communities
给定上面的 User.rb,调用“current_user.posts”返回一个或多个与 current_user 相同的社区的帖子。
问题:
我希望改进该关联,以便调用“current_user.posts”仅返回其社区是 current_user 社区的完整子集的那些帖子。
因此,给定一个具有 [1,2,3] 的 community_ids 的 current_user,调用“current_user.posts”只会产生那些“community_ids”数组为 1 的帖子。 、[2]、[3]、[1,2]、[1,3]、[2,3] 或 [1,2,3]。
我一直在研究范围 here ,但似乎无法确定如何成功完成此操作...

最佳答案

好问题...

我的即时想法:

——

ActiveRecord Association Extension

这些基本上允许您创建一系列关联方法,允许您确定特定标准,如下所示:

#app/models/user.rb
has_many :communities, through: :community_users
has_many :posts, through: :communities do
def in_community
where("community_ids IN (?)", user.community_ids)
end
end

——

Conditional Association

您可以在关联中使用条件,如下所示:
#app/models/user.rb
has_many :posts, -> { where("id IN (?)", user.community_ids) }, through: :communities #-> I believe the model object (I.E user) is available in the association

——

Source

我原本认为这是你最好的选择,但更深入地研究它,我认为只有当你想使用不同的关联名称时

Specifies the source association name used by has_many :through queries. Only use it if the name cannot be inferred from the association. has_many :subscribers, through: :subscriptions will look for either :subscribers or :subscriber on Subscription, unless a :source is given.



老实说,这是需要思考的问题之一

首先,您如何存储/调用 community_ids数组?是直接存储在db中,还是通过ActiveRecord方法访问 Model.association_ids ?

期待进一步帮助您!

关于ruby-on-rails - has_many 上的自定义范围,:through association (Rails 4),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23716674/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com