我有一个Rails 4应用程序,我正在尝试使用3个可选参数对我的发票进行简单搜索:客户端名称,开始日期,结束日期。
搜索工作正常,如果我将开始日期和结束日期用于<和>,但是虽然我使用了> =和< =,但如果发票日期与开始或结束相同,它就不会显示在结果列表中。
使用的表格如下:
Client Table
ID
Name
The rest of the fields aren't necessary
Invoice Table
ID
Client_ID
Total_Price
Created_At *only here for relevance*
我的发票控制器搜索方法如下所示:
def search
if request.post?
@count = 0
@invoices = Invoice.all
if params[:start_date].present?
@invoices = Invoice.invoices_by_date(@invoices, params[:start_date], 'start')
if @invoices.present?
@count = 1
else
@count = 2
end
end
if params[:end_date].present?
@invoices = Invoice.invoices_by_date(@invoices, params[:end_date], 'end')
if @invoices.present?
@count = 1
else
@count = 2
end
end
if params[:name].present?
@invoices = Invoice.invoices_by_client(@invoices, params[:name])
if @invoices.present?
@count = 1
else
@count = 2
end
end
if @count == 2
flash.now[:danger] = "No results found."
@invoices = nil
end
@name = params[:name]
@start_date = params[:start_date]
@end_date = params[:end_date]
end
end
我使用的发票模型方法如下所示:
def self.invoices_by_client(invoices, name)
invoices= invoices.includes(:client)
.select('invoices.created_at', 'invoices.total_price', 'clients.name')
.where("clients.name LIKE ?", "%#{name}%")
.references(:client)
return invoices
end
def self.invoices_by_date(invoices, date, modifier)
if modifier == 'start'
invoices = invoices.includes(:client)
.select('invoices.created_at', 'invoices.total_price', 'clients.name')
.where("invoices.created_at >= ?", date)
.references(:client)
elsif modifier == 'end'
invoices = invoices.includes(:client)
.select('invoices.created_at', 'invoices.total_price', 'clients.name')
.where("invoices.created_at <= ? ", date)
.references(:client)
end
return invoices
end
它可能不是最好的解决方案,我不知道我是否做错了所以如果你们能帮我解决这个问题会很棒。
答案 0 :(得分:0)
我遵循了亚历杭德罗的建议并且把时间和日期混为一谈,这样的事情:
if modifier == 'start'
invoices = invoices.includes(:client)
.select('invoices.created_at', 'invoices.total_price', 'clients.name')
.where("invoices.created_at >= ?", "#{date} 00:00:00") // Added the start time
.references(:client)
elsif modifier == 'end'
invoices = invoices.includes(:client)
.select('invoices.created_at', 'invoices.total_price', 'clients.name')
.where("invoices.created_at <= ? ", "#{date} 23:59:59") // Added end time aswell
.references(:client)
end
我将开始日期的时间强制为00:00:00,将结束日期的时间强制为23:59:59,并且按预期工作。谢谢你的帮助,我希望这有助于其他人!