从复杂查询中获取关联的ActiveRecord :: Relation

时间:2013-12-03 17:14:23

标签: sql ruby-on-rails activerecord

我有以下AR模型:

class Checkin < ActiveRecord::Base
    belongs_to :user
end

class User < ActiveRecord::Base
    has_many :checkins
end

假设我有关于签名和用户的复杂查询,例如Checkin.nearby.todayUser.friends_of(john)。有没有一种简单的方法可以得出ActiveRecord::Relation Users?最终结果将是今天在附近办理登机手续的约翰的朋友。

我希望最终结果是ActiveRecord::Relation的实例。

谢谢!

1 个答案:

答案 0 :(得分:0)

这应该这样做:

users = User.friends_of(john)
users = users.joins(:checkins).where(checkins: { checkin_date: Date.today })
users = users.where( # your logic to determine the nearby )

正如您所看到的,有关附近范围缺失的逻辑。

在自定义方法中:

def self.friends_checked_nearby_at_date(friend, nearby = true, date = Date.today)
  users = User.friends_of(friend)
  users = users.joins(:checkins).where(checkins: { checkin_date: date })
  users = users.where( # your logic for the nearby scope ) if nearby.present?

  return users
end

# usage:
User.friends_checked_nearby_at_date( User.first )
# or 
User.friends_checked_nearby_at_date( User.first, true, Date.today-1.week )
# or
User.friends_checked_nearby_at_date( User.first, false )
# etc.