我的模特
class House < ActiveRecord::Base
has_many: bookings
end
class Booking < ActiveRecord::Base
belongs_to: house
end
预订表的字段为customer_name,start_time,end_time等。
我想在房屋页面索引页面上创建一个搜索表单(start_time,end_time),以便访问者可以检查在给定时间段内房屋是否可用。
有人想法如何开始?
Thanks..remco
答案 0 :(得分:1)
在视图中,声明一个非链接到任何对象的表单
<% form_tag :url => search_book_path, :method => :get do %>
<%= text_field_tag :start_time %>
<%= text_field_tag :end_time %>
<%= submit_tag %>
<% end %>
在书籍上添加路线
map.resource :books, :collection => { search => :get }
在book_controller中,声明函数搜索:
def search
start_time = params[:start_time] || DateTime.now
end_time = params[:end_time] || DateTime.now
@books = Book.search(start_time, end_time)
end
然后在Book model
上声明搜索def search(start_time_, end_time_)
return Book.find(:all, :conditions => [
"#{Book.table_name}.start_time >= ? AND #{book.table_name}.end_time <= ?",
start_time_,
end_time_]
)
end
不确定所有语法,但这应该会给你一个想法。
编辑:我不明白所有问题。模型函数search
应搜索可用的房屋:
喜欢这个
def search_for_availability_between(start_time_, end_time_)
return Book.find(:all, :conditions => [
"#{Book.table_name}.start_time > ? AND #{book.table_name}.end_time < ?",
end_time_,
start_time_]
)
end
你应该通过测试来检查它,但我认为它应该有用。
答案 1 :(得分:0)
@books = Book.available_house(start_time, end_time)
在Book模型中,您可以使用范围
in House Model
def available_house(start, finish)
where("id not in (select t.house_id from timings t where (t.start_time between ? and ?) || (t.end_time between ? and ?) )", start,finish,start,finish)
end