在Rails中构建一个简单的搜索表单? [英] building a simple search form in Rails?
问题描述
我正在尝试在Ruby on Rails中构建一个简单的搜索表单,该表单非常简单,基本上,您可以从一系列选项中选择字段,然后显示与该字段匹配的所有事件。当我将任何字段留空时,问题就来了。
I'm trying to build a simple search form in Ruby on Rails, my form is simple enough basically you select fields from a series of options and then all the events matching the fields are shown. The problem comes when I leave any field blank.
这是负责过滤参数的代码
Here is the code responsible for filtering the parameters
Event.joins(:eventdates).joins(:categories).where
("eventdates.start_date = ? AND city = ? AND categories.name = ?",
params[:event][:date], params[:event][:city], params[:event][:category]).all
从我得到的结果是,它查找具有任何空字段的事件,但是由于所有事件都不具有空字段,因此除非所有3个字段都被填充,否则它将不匹配,所以当我尝试说在范围内或范围内查找事件时会出现另一个问题日期数组,我对如何将多天输入搜索一无所知。
From what I get it's that it looks for events with any empty field, but since all of them have them not empty, it wont match unless all 3 are filled, another problem arises when I try to say, look events inside a range or array of dates, I'm clueless on how to pass multiple days into the search.
我对制作搜索表单一般来说还很陌生,所以我不甚至知道这是否是最好的方法,我也试图在不使用特殊模型的情况下保留搜索。
I'm pretty new to making search forms in general, so I don't even know if this is the best approach, also I'm trying to keep the searches without the need of a secialized model.
推荐答案
下面可能是您想要的。 (注意:如果所有字段均为空白,则会显示事件表中可与事件日期和类别链接的所有数据。)
Below is probably what you are looking for. (Note: If all fields all blank, it shows all data in the events table linkable with eventdates and categories.)
events = Event.joins(:eventdates).joins(:categories)
if params[:event]
# includes below where condition to query only if params[:event][:date] has a value
events = events.where("eventdates.start_date = ?", params[:event][:date]) if params[:event][:date].present?
# includes below where condition to query only if params[:event][:city] has a value
events = events.where("city = ?", params[:event][:city]) if params[:event][:city].present?
# includes below where condition to query only if params[:event][:city] has a value
events = events.where("categories.name = ?", params[:event][:category]) if params[:event][:category].present?
end
要使用多天进行搜索:
# params[:event][:dates] is expected to be array of dates.
# Below query gets converted into an 'IN' operation in SQL, something like "where eventdates.start_date IN ['date1', 'date2']"
events = events.where("eventdates.start_date = ?", params[:event][:dates]) if params[:event][:dates].present?
这篇关于在Rails中构建一个简单的搜索表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!