1

使用我当前的设置,我需要添加一些自定义 SQL 语句,以使用 Tire Gem 限定一些数据。

我正在使用带有 Ruby 1.9.3 的 Rails 3.2

在我的列表控制器中,我有以下内容:

@listings = Listing.search()

对于我的 Listing.rb,我使用了带有许多过滤器的搜索方法,例如:

def self.search(params={})
    tire.search(load: true, page: params[:page], per_page: 50) do |search|
      search.query  { string params[:query], :default_operator => "AND" } if params[:query].present?
      search.filter :range, posted_at: {lte: DateTime.now}
      search.filter :term, "property.rooms_available"   => params[:property_rooms_available]  if params[:property_rooms_available].present?
      search.filter :term, "property.user_state"        => params[:property_user_state]       if params[:property_user_state].present?
  
   ...
end

我需要做的是将此 SQL 语句添加到搜索方法中,以便它的范围是经度和纬度。“坐标”通过 URL 中的参数以形式传入

http://localhost:3000/listings?coords=51.0000,-01.0000 52.0000,-02.0000 

(-01.0000 和 52.0000 之间有一个空格。)

目前我有:

 sql = "SELECT title, properties.id, properties.lng,properties.lat from listings WHERE ST_Within(ST_GeometryFromText('POINT(' || lat || ' ' || lng || ')'),ST_GeometryFromText('POLYGON((#{coords}))'));"

我考虑过尝试通过这样的方式在控制器内限定它?

def self.polyed(coords)
    joins(:property).
    where("ST_Within(ST_GeometryFromText('POINT(' || properties.lat || ' ' || properties.lng || ')'),ST_GeometryFromText('POLYGON((#{coords}))'))").
    select("title, properties.id, properties.lng,properties.lat")
end

和这个...

Listings_controller.rb

def index
  @listings = Listing.polyed(poly_coordinates).search()
end

它需要以 HTML 和 json 格式将结果作为@listings 返回

http://localhost:3000/listings.json?

我已经在使用 RABL 来自动生成 json。

这可能吗?

提前谢谢了。

瑞安

4

1 回答 1

0

一种可能性是在选项中传递选项joins,where:load

但是如果你想在 Rails 代码中过滤返回的结果,一个更好的方法似乎是只加载带有 Tire 的记录 ID(使用fields选项来限制返回的字段),然后在你的 SQL 查询中使用它们。

于 2012-12-12T20:58:07.597 回答