0

我有一个带有字段年份类型字符串的汽车脚手架。我很感兴趣在两个 select_box 之间选择两年并显示所选年份之间的汽车。

我开始在控制台中进行测试:

Car.maximum(:year)

Car.minimum(:year)

但是当我开始测试时:

Car.where((self.maximum(:year))..(self.minimum(:year)))

头晕脑胀,欢迎提出建议,谢谢!

解决方案

在模型 cars.rb 中添加一个方法:

def self.year(fyear,tyear)
  result = order('new DESC')
  result = where(:year => fyear..tyear) if fyear.present? && tyear.present? 
  result
end

然后在 cars_controller.rb 中添加 index 方法:

@cars = Car.year(params[:fyear],params[:tyear])

最后,在视图 index.html.erb 添加您选择两年字段的表单:

<%= form_for cars_path, :method => :get do %>
  <label>Mínimo</label>
  <%= select_tag :fyear, options_for_select(Car.all.map &:year) %>
  <br />
  <label>Máximo</label>
  <%= select_tag :tyear, options_for_select(Car.all.map &:year) %>
  <br />
  <%= submit_tag "Buscar", :name => nil %>
</form>
<% end %>

谢谢 beck03076、user2564200 和 Abimael Martell

4

2 回答 2

0

我认为这可以帮助你:D。

http://guides.rubyonrails.org/active_record_querying.html#range-conditions

于 2013-07-11T22:56:33.537 回答
0

将模型方法更改为此,

    def self.search(search,from,to) 
      result = order('new DESC') 
      result = joins(:model => :brand).where('brands.title LIKE ? OR    models.title LIKE ? AND cars.year BETWEEN ? AND ?', "%#{search}%", "%#{search}%",from,to).order('new DESC') if search.present? 
      result
    end 

并像这样从控制器调用它,

#@cars = Car.search("Volkswagen Vento",2007,2009)
@cars = Car.search(params[:query],params[:from],params[:to])
于 2013-07-11T14:52:33.923 回答