title: How to add conditional where clauses in rails
body: <p>I am a rails newbie and am trying to perform a search on a table with rails, and i'm just using my sql knowledge to do this. But this just doesn't seems like rails or ruby even...</p>
  
  <p>Is there any better way to do what i'm doing below? (basically, only pass date arguments to sql if they are filled)</p>
  
  <pre><code>def search(begin_date=nil, end_date=nil)
  
      subject = " and created_at "
  
      if !(begin_date.nil? || end_date.nil?)
        where_part = subject + "BETWEEN :begin_date AND :end_date"
      else if (begin_date.nil? &amp;&amp; end_date.nil?) 
        where_part = ""
      else if(begin_date.nil?)
        where_part = subject + " &lt;= :end_date"
      else if (end_date.nil?)
        where_part = subject + " &gt;= :begin_date"
      end
      end
      end
      end
  
      User.joins(places: {containers: {label: :user}}).where("users.id= :user_id "+where_part, user_id: self.id, begin_date:begin_date, end_date:end_date).group(...).select(...)
  end
  </code></pre>
  
  <p><strong>EDIT</strong></p>
  
  <p>user.rb</p>
  
  <pre><code>has_many :containers
  has_many :user_places
  has_many :places, through: :user_places
  has_many :labels
  </code></pre>
  
  <p>place.rb</p>
  
  <pre><code>has_many :containers
  has_many :user_places
  has_many :users, through: :user_places
  </code></pre>
  
  <p>container.rb</p>
  
  <pre><code>belongs_to :label
  belongs_to :place
  belongs_to :user
  </code></pre>
  
  <p>label.rb</p>
  
  <pre><code>belongs_to :user
  has_many :containers
  </code></pre>
  
  <p>Basically, i want to get a count of the number of containers within a given user's labels or with a direct relationship, per location, and want to be able to filter it by begin and end dates.</p>
  
  <p>Either of this dates may be nil, and so i would need to address this in my "query".</p>
  
  <p>My question is : How can i do this the rails way? I took a look at <a href="http://guides.rubyonrails.org/active_record_querying.html" rel="nofollow noreferrer">http://guides.rubyonrails.org/active_record_querying.html</a> and perhaps i could use the except command here somewhere...but this relationship model just seems a bit complex to do this with ActiveRecord...how may I?, i really think i should use ActiveRecord, but how?</p>
  
  <p>Thank you</p>