Rails public_activity feed具有多态跟随

时间:2013-03-08 03:00:43

标签: ruby-on-rails feed polymorphic-associations

我在我的应用中使用了两个宝石,public_activity和acts_as_follower。我已经将acts_as_follower设置得很好,用户可以关注其他用户以及乐队。

问题是从您关注的对象中提取活动。使用公共活动,我使用推荐的方法获得全局Feed:

@activities = PublicActivity::Activity.order("created_at desc")

工作正常。不过,我还希望有一个以下的提要,这将提供以下内容:

@activities = PublicActivity::Activity.order("created_at desc").where(owner_id: current_user.all_following, owner_type: ????????)

如果不指定owner_type,则仅使用owner_id创建提要,这是一个问题,因为用户和乐队可以具有相同的ID。在这种情况下,我如何指定所有者类型?

2 个答案:

答案 0 :(得分:1)

对于用户:

@activities = PublicActivity::Activity.where(owner_id: current_user.follows_by_type('User'), owner_type: 'User').order("created_at desc")

乐队:

@activities = PublicActivity::Activity.where(owner_id: current_user.follows_by_type('Band'), owner_type: 'Band').order("created_at desc")

混合物:

@activities = PublicActivity::Activity.where("(owner_id IN (?) AND owner_type = 'User') or (owner_id IN (?) AND owner_type = 'Band')", current_user.follows_by_type('User'), current_user.follows_by_type('Band')).order("created_at desc")

答案 1 :(得分:0)

Owen,在这里你使用所谓的polymorphic associations试图弄清楚它们是如何工作的。 它只是将数据库放入数据库,而不仅仅是对象的类型。