Rails - 使用范围来检查当前日期是否存在记录的正确方法是什么

时间:2015-12-18 20:08:06

标签: ruby-on-rails ruby-on-rails-4

在我们的网站中,我们将拥有搜索记录功能,以便用户查看和检索当天的最后x次搜索。

我想在创建新记录之前检查用户是否尚未为当天输入相同的关键字。在删除之前,这些记录将保留在数据库中几天,因此,如果我只是验证关键字的唯一性并且用户过去输入了该关键字,则不会创建记录。

以下是我的模型和控制器设置的方法。忍受我,我还在学习铁轨和示波器。

MODEL

class UserLog < ActiveRecord::Base

   belongs_to :user
   validates :user_id, presence: true
   validates :query_type, presence: true
   validates :keyword, presence: true
   validates :url, presence: true

   validates_uniqueness_of :id

   scope :user_searches, -> (user = nil) {where(user_id: user).order(created_at: :desc)}
   scope :today_only, -> {where(created_at: Time.now.beginning_of_day..Time.now.end_of_day)}

end

我相信我可以在我的模型中添加这些可以做我想要的检查。

validates_uniqueness_of :keyword, scope: :keyword, conditions: -> {where(created_at: Time.now.beginning_of_day..Time.now.end_of_day)}

OR THIS?

validates_uniqueness_of :keyword, conditions: -> {where(created_at: Time.now.beginning_of_day..Time.now.end_of_day)}

和控制器

# to save user query in db
if query_valid (other checks in controller)  
  UserLog.create(user_id: current_user.id, query_type: query_type, keyword: query_value, url: request.fullpath)
end

并根据用户请求显示记录

@recent_searches = UserLog.user_searches(current_user).today_only.limit(15)

1 个答案:

答案 0 :(得分:1)

整个Time.now.beginning_of_day..Time.now.end_of_day声音过于复杂。你如created_on那样存储created_at,而不是Date,而不是DateTime。您的唯一性范围变得更加容易,类似的创建可能是:

current_user.logs.where(keyword: query_value, created_on: Date.today).first_or_create(other_fields)

我假设用户为has_many :logs,以提高可读性。而不是UserLog.create(user_id: current_user.id, ...