2016-07-16 72 views
0

通过使用railscast视频,我创建了一个适用于相同模型的简单搜索。我有日期,日期和时间的字段。如何按日期和日期搜索模型

我的模型

class Sale < ApplicationRecord 
    belongs_to :washer, optional: true 
    belongs_to :location, optional: true 

    has_many :sale_services 
    has_many :services, :through => :sale_services 

    def day 
    created_at.strftime('%A') 
    end 

    def time 
    created_at.strftime("%H:%M") 
    end 

    def date 
    created_at.strftime('%F') 
    end 


def self.search(search) 
    if search 
     key = "'%#{search}%'" 
     columns = %w{ city station venue area country plate_number } 
     joins(:services).joins(:washer).joins(:location).where(columns.map {|c| "#{c} ILIKE #{key}" }.join(' OR ')) 
    else 
     where(nil) 
    end 
    end 
end 

我需要做什么改变,以确保我可以搜索一天,日期时间戳字段?

回答

0

你可以使用下面的代码作为参考,我已经在created_at字段上试过这个ant,它适用于我。

Model.where('extract(year from date_column) = ?', desired_year) 
Model.where('extract(month from date_column) = ?', desired_month) 
Model.where('extract(day from date_column) = ?', desired_day_of_month) 

这里是stackoverflowlink,你可以检查,如果上面的代码不为你工作。