简单的活动记录查询

时间:2014-06-17 22:57:38

标签: ruby-on-rails ruby-on-rails-4 rails-activerecord

我觉得这个问题很简单,但也许我只是在思考它..

我有一个Active Record查询,如下所示:

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

这很有效,但我想将current_user添加为:owner。所以我尝试了很多选项,包括:

@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")

但是我收到的错误如下:

Cannot visit User::ActiveRecord_Associations_CollectionProxy

任何人都可以发现我犯的错误......谢谢

2 个答案:

答案 0 :(得分:2)

current_user.followed_usersActiveRecord_Associations_CollectionProxy,但您只需要ID,{ - 1}}

使用您的示例,完整查询将如下所示:

current_user.followed_users.collect(&:id)

答案 1 :(得分:2)

您可以将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")

或者您只需将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")