简体   繁体   English

简单的活动记录查询

[英]Simple active record query

I have a feeling this question is easy, but maybe I am just overthinking it.. 我觉得这个问题很容易,但是也许我只是想得太过分了。

I have an Active Record query that looks like this: 我有一个Active Record查询,看起来像这样:

@activities = PublicActivity::Activity.includes(:owner, :trackable).where(owner_id: current_user.followed_users, owner_type: "User", kind: "Activity")

This works great, but I'd like to add current_user as a possible :owner . 这很好用,但是我想将current_user添加为可能的:owner So I've tried many options, including: 因此,我尝试了许多选择,包括:

@activities = PublicActivity::Activity.includes(:owner, :trackable).where(owner_id: [[current_user.followed_users], [current_user]], owner_type: "User", kind: "Activity")
@activities = PublicActivity::Activity.includes(:owner, :trackable).where(owner_id: [current_user.followed_users, current_user], owner_type: "User", kind: "Activity")

However I'm getting errors like: 但是我遇到了类似的错误:

Cannot visit User::ActiveRecord_Associations_CollectionProxy

Can anyone spot the mistake I'm making...thanks 任何人都可以发现我犯的错误...谢谢

current_user.followed_users is an ActiveRecord_Associations_CollectionProxy , but you only want the ids, like so - current_user.followed_users.collect(&:id) current_user.followed_users是一个ActiveRecord_Associations_CollectionProxy ,但您只需要ID,就像这样current_user.followed_users.collect(&:id)

Using your example, the full query would look something like this: 使用您的示例,完整查询如下所示:

@activities = PublicActivity::Activity.includes(:owner, :trackable).where(owner_id: [[current_user.followed_users.collect(&:id)], [current_user.id]], owner_type: "User", kind: "Activity")

You can append the current_user to the array of followed_users. 您可以将current_user追加到followed_users数组中。 Try this: 尝试这个:

allowed_users = current_user.followed_users << current_user
@activities = PublicActivity::Activity.includes(:owner, :trackable).where(owner_id: allowed_users, owner_type: "User", kind: "Activity")

Or you can just add current_user as a one element array to the their followed_users . 或者,您可以仅将current_user作为一个元素数组添加到其followed_users

allowed_users = current_user.followed_users + [current_user]
@activities = PublicActivity::Activity.includes(:owner, :trackable).where(owner_id: allowed_users, owner_type: "User", kind: "Activity")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM