当前位置: 动力学知识库 > 问答 > 编程问答 >

ruby on rails - The best way to combine two active record queries

问题描述:

What difference between two approaches shown below and what is better:

 user.photos & Photo.public

and

 user.photos.where('photos.id IN (?)', Photo.public.select(:id))

Is there better way to combine two active record queries ?

网友答案:

The first will be using an array join, the second is doing two queries, neither is as efficient as adding another scope to your Photo model:

 # Photo Model
  scope :public, where {:public => true }
  scope :user, lambda { |user| where("user_id = ?", user) }

  # Controller
  Photo.public.user(user)
网友答案:

Given that Photo#public is a scope, ex.:

scope :public, -> { where(:public => true) }

You can simply write

user.photos.public
网友答案:

In the case you can't use a new scope, I would suggest you:

user.photos.merge(Photo.public)
分享给朋友:
您可能感兴趣的文章:
随机阅读: