如何使用可选部件构建ActiveRecord查询?

时间:2014-05-27 20:45:49

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

我想知道,根据我是否有参​​数,我怎么能有多个条件?

以下方法不起作用,这是有道理的:

scope :within_distance, ->(point, radius=10000, _supplier=nil) {
  joins(:address)
  unless _supplier.nil?
    .where(:supplier => _supplier)
  end
  .where("ST_DWithin(lonlat,'#{point.as_text}'::geography ,#{radius},true)")
  .order("ST_Distance(lonlat, ST_GeomFromText('#{point.as_text}', #{SRID}))")
}

1 个答案:

答案 0 :(得分:1)

这是你想要做的,但是在有效的Ruby中。使用局部变量来构建查询。

scope :within_distance, ->(point, radius=10000, _supplier=nil) {
  query = joins(:address)
  unless _supplier.nil?
    query = query.where(:supplier => _supplier)
  end
  query.where("ST_DWithin(lonlat,'#{point.as_text}'::geography ,#{radius},true)")
    .order("ST_Distance(lonlat, ST_GeomFromText('#{point.as_text}', #{SRID}))")
}