Sakti
Sakti

Reputation: 31

How to search by date range

I'm still learning in RoR and I have a problem to search table column (period) by date range (start_period, end_period). This is my code :

promotions_controller

  def search
    @promotions = Promotion.search(params)
    respond_to do |format|
      format.js
    end
  end

index.html.erb - promotions

<%= form_tag search_promotions_path, class: "form-horizontal bucket-form", remote: true do %>
  <div class="col-md-6">
    <div class="form-group">
      <td>Periode</td>
        <div class="input-group input-large">
          <%= text_field_tag 'start_period','', class: "form-control dpd1" %>
          <span class="input-group-addon">To</span>
          <%= text_field_tag 'end_period','', class: "form-control dpd1" %>
        </div>
    </div>
  </div>
<% end %>

promotion.rb

def self.search(params)
  promotions = Promotion.all
  ????
end

I have tried to create a code for (start_period) & (end_period) in my model. But I have failed :( Can you give me a solution for my problem? Thanks

Upvotes: 2

Views: 1193

Answers (1)

Try the following method:

def self.search(start_period, end_period)
  Promotion.where("start_period >= ? AND end_period <= ?", start_period, end_period)
end

If you place these records on your seeds file (rake db:seed):

Promotion.create!([
  {name: 'p1', start_period: DateTime.new(2001), end_period: DateTime.new(2002)},
  {name: 'p2', start_period: DateTime.new(2001), end_period: DateTime.new(2003)},
  {name: 'p3', start_period: DateTime.new(2008), end_period: DateTime.new(2009)}
])

And execute

Promotion.search(DateTime.new(1999), DateTime.new(2004)) # returns p1 & p2

Upvotes: 1

Related Questions