如何按日期范围搜索

时间:2015-10-12 18:45:09

标签: ruby-on-rails-4

我还在学习RoR,我有一个问题是按日期范围(start_period,end_period)搜索表格列(句点)。这是我的代码:

promotions_controller

textview = (TextView) findViewById(R.id.greetings_text_view);

index.html.erb - 促销活动

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

promotion.rb

<%= 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 %>

我尝试为(start_period)&amp;创建代码(end_period)在我的模型中。但我失败了:(你能解决我的问题吗?谢谢

1 个答案:

答案 0 :(得分:1)

尝试以下方法:

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

如果您将这些记录放在种子文件(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)}
])

执行

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