title: Rails - What's the proper way to use scopes to check if a record exists for the current day only
body: <p>In our website we will have a search history feature so users can view and retrieve their last x number of searches for the current day.</p>
  
  <p>I would like to check that the user hasn't already entered the same keyword for <strong>the current day</strong> before creating a new record. These records would be kept in the db for a few days before being removed so if I just validate the uniqueness of the keyword and the user entered that keyword in the past, the record would not be created. </p>
  
  <p>Below is how I have my model and controller setup. Bear with me, I'm still learning about rails and scopes.</p>
  
  <p><strong>MODEL</strong></p>
  
  <pre><code>class UserLog &lt; 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, -&gt; (user = nil) {where(user_id: user).order(created_at: :desc)}
     scope :today_only, -&gt; {where(created_at: Time.now.beginning_of_day..Time.now.end_of_day)}
  
  end
  </code></pre>
  
  <p><strong>I believe I could add these checks in my model that would do what I want.</strong></p>
  
  <pre><code>validates_uniqueness_of :keyword, scope: :keyword, conditions: -&gt; {where(created_at: Time.now.beginning_of_day..Time.now.end_of_day)}
  
  OR THIS?
  
  validates_uniqueness_of :keyword, conditions: -&gt; {where(created_at: Time.now.beginning_of_day..Time.now.end_of_day)}
  </code></pre>
  
  <p><strong>And the controller</strong></p>
  
  <pre><code># 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
  </code></pre>
  
  <p><strong>And to get records to display on user request</strong></p>
  
  <pre><code>@recent_searches = UserLog.user_searches(current_user).today_only.limit(15)
  </code></pre>