1

我正在尝试使用宝石轮胎在我的应用程序中进行搜索。我有表格区域、城市、酒店、房间和房间信息。

我需要的是通过查询和其他文本字段(如 date_from、date_to 和房间数)查找酒店。在模型中,我有计算酒店是否有空闲房间并发送布尔值的方法。如何使用此布尔方法过滤查询?

谢谢

在hotel.html.erb

<%= form_tag search_hotels_path, :method => 'post' do %>
  <%= label_tag :query %>
  <%= text_field_tag :query, params[:query] %>
  <%= label_tag 'From' %>
  <%= text_field_tag :date_f, params[:date_from] %>
  <%= label_tag 'To' %>
  <%= text_field_tag :date_to, params[:date_to] %>
  <%= label_tag 'Rooms' %>
  <%= text_field_tag :rooms, params[:rooms] %>
  <%= submit_tag :search %>
<% end %>

在酒店.rb

class Hotel < ActiveRecord::Base
include Tire::Model::Search
include Tire::Model::Callbacks

belongs_to :city
belongs_to :area
has_one :area, :through => :city
has_many :rooms, :dependent => :delete_all


def search(params)

        tire.search do
            query do
                boolean do  
                    must { string params[:query] } if params[:query].present?
                    must { term rooms_available params, true}
                end
            end 
        end

end

self.include_root_in_json = false
def to_indexed_json
    to_json(methods: [:area_name,:city_name])
end

def area_name
    city.area.name
end
def city_name
    city.name
end


def rooms_available params
    exit
    begin_date = params[:date_from].to_date
    end_date = params[:date_to].to_date
    number_of_rooms = params[:rooms]

    rooms.each do |room|
        if room.available(begin_date, end_date, number_of_rooms)
            return true
        end
    end
    return false
end

end
4

1 回答 1

4

把它放在 to_json 方法中:

def to_json
  {
    :area_name => self.area_name, 
    :city_name => self.city_name,
    :rooms_available => self.rooms_available
   }.to_json
end

然后:

def search(params)

    tire.search do
        query do
            boolean do  
                must { string params[:query] } if params[:query].present?
                must { term rooms_available, true}
            end
        end 
    end

end

但是在这种情况下,最好将 rooms_available 放在过滤器中,因为这是必须的,而且您不关心对该子句的评分。

def search(params)

    tire.search do
        query do
            boolean do  
                must { string params[:query] } if params[:query].present?
            end
        end 
        filter do
            boolean do  
               must { term rooms_available, true}
            end
        end
    end

end

希望这可以帮助 :)

于 2012-06-22T22:36:39.230 回答