sql - Show results between :year field in Rails 3 -


i haved cars scaffold field year type string. im interesting select 2 years between 2 select_box , display cars between selected years.

i started testing in console with:

car.maximum(:year) 

and

car.minimum(:year) 

but when starting testing with:

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

i lost head, suggestions welcome, thank you!

the solution

in model cars.rb add method:

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

then in cars_controller.rb add index method:

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

finally, on view index.html.erb add form select 2 year fields:

<%= form_for cars_path, :method => :get %>   <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 %> 

thank beck03076, user2564200 , abimael martell

change model method this,

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

and call controller this,

#@cars = car.search("volkswagen vento",2007,2009) @cars = car.search(params[:query],params[:from],params[:to]) 

Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -