【问题标题】:Wishing for elegant ActiveRecord chaining希望优雅的 ActiveRecord 链接
【发布时间】:2013-05-11 06:58:24
【问题描述】:

在我的 Rails 3 应用中,我的用户拥有:

有一个动作需要显示我朋友的活动。

我希望通过这样的链来做到这一点(我的问题是:我该怎么做?):

@activities = current_user.friends.activities

但它不起作用,因为current_user.friends 返回一个 ActiveRecrord::Relation 对象。

undefined method `activities' for #<ActiveRecord::Relation:0xc4d7770> 

我必须像这样查询它们:

@activities = PublicActivity::Activity.where(owner_id: current_user.friend_ids)

它工作正常,但它不像我想要的那样优雅:)

那么,有没有更优雅的方式来使用链式查询朋友的操作?

用户模型如下所示:

class User < ActiveRecord::Base
  has_many :friendships
  has_many :friends, through: :friendships  # 

  has_many :activities, class_name: "::PublicActivity::Activity", as: :owner
  # ...
end

class Friendship < ActiveRecord::Base
  belongs_to :user
  belongs_to :friend, class_name: "User"
end

【问题讨论】:

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


【解决方案1】:

如果我正确阅读了您正在寻找的内容,那么您似乎正在尝试加入。

ActiveRecord支持通过includes调用进行预加载,也可以有条件。

http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations

我认为这可以解决您的问题。

【讨论】:

  • 实际上,join 或 include 不是问题——我只是在寻找一些更优雅的 AR 查询方式。无论如何谢谢:)
猜你喜欢
  • 2021-03-14
  • 2011-03-31
  • 1970-01-01
  • 1970-01-01
  • 2022-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多