除了我在用户和艺术家模型之间设置的多态活动跟踪之外,我还在使用acts_as_follower gem。我现在正试图在用户的节目视图中显示所关注艺术家的所有活动。起初我以为我可以使用gem的all_follows方法简单地创建一个艺术家的实例变量:
current_user.all_follows
=> #<ActiveRecord::AssociationRelation [#<Follow id: 8, followable_id: 1, followable_type: "Artist", follower_id: 1, follower_type: "User", blocked: false, created_at: "2016-02-29 12:56:31", updated_at: "2016-02-29 12:56:31">]>
正如您所看到的,它返回Follow
个对象与我想要检索的Artist
个对象。我通过在Activity
类上执行sql查询来获得另一个想法:
Activity.where(followable_id: current_user.follows.pluck(&:id))
这给了我错误:
SQLite3::SQLException: no such column: activities.followable_id: SELECT "activities".* FROM "activities" WHERE "activities"."followable_id" IN (8, 1, 'Artist', 1, 'User', 'f', '2016-02-29 12:56:31.974244', '2016-02-29 12:56:31.974244')
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: activities.followable_id: SELECT "activities".* FROM "activities" WHERE "activities"."followable_id" IN (8, 1, 'Artist', 1, 'User', 'f', '2016-02-29 12:56:31.974244', '2016-02-29 12:56:31.974244')
检索这些记录的最佳方法是什么?
class Artist < ActiveRecord::Base
has_many :activities, as: :owner, dependent: :destroy
acts_as_followable
end
class User < ActiveRecord::Base
acts_as_follower
end
class Activity < ActiveRecord::Base
belongs_to :trackable, polymorphic: true
belongs_to :owner, polymorphic: true
end
class Follow < ActiveRecord::Base
extend ActsAsFollower::FollowerLib
extend ActsAsFollower::FollowScopes
belongs_to :followable, polymorphic: true
belongs_to :follower, polymorphic: true
end
class UsersController < ApplicationController
def show
@artist_activity = Activity.where(followable_id: current_user.follows.pluck(&:id))
end
end
答案 0 :(得分:0)
这似乎对我有用:
Activity
.where(owner_type: 'Artist')
.where(:owner_id => current_user.all_follows
.where(followable_type: 'Artist')
.map(&:followable)
.map{|artist| artist.id}
)
可能更好:
Activity.where(owner: current_user.all_follows
.where(followable_type: 'Artist')
.map(&:followable)
)
但我没有测试过。
所以,这一点:
current_user.all_follows
.where(followable_type: 'Artist')
.map(&:followable)
凭借.map(&followable)
位创建一个对象数组。在这种情况下,由于.where(followable_type: 'Artist')
,它恰好是Artist对象的数组。
Activity
规定所有者是多态的。因此,当传入一个对象数组时,AR足够聪明,以便在owner_type
和owner_id
上匹配 - 所以你不必像我在第一个例子中那样明确。
订购:
Activity.where(owner: current_user.all_follows
.where(followable_type: 'Artist')
.map(&:followable)
).order(created_at: :desc)
答案 1 :(得分:0)
最初是在正确的轨道上,但应该由所有者(即艺术家)查询,并从那里收集并采摘他们的followable_id
:
class UsersController < ApplicationController
def show
@artist_activity = Activity.order("created_at desc").where(owner: current_user.all_follows.pluck(&:followable_id))
end
end