Richlewis
Richlewis

Reputation: 15374

Search query via controller or model

I am looking at a Ryan Bates screen cast (albeit an older one) where he is implementing some simple search functionality. I am just looking to get a better understanding as I am looking to implement something slightly more complicated in my application.

In his controller he has

def index  
 @products = Product.search(params[:search]).paginate(:per_page => 5, :page => params[:page])  
end 

and then a class method (in model) of

def self.search(search)  
 if search  
  find(:all, :conditions => ['name LIKE ?', "%#{search}%"])  
 else  
  find(:all)  
 end  
end  

His search method is in his model where as im my application i build my search query in my controller

class PublicController < ApplicationController 

def rehomed
 conditions = {}
 conditions.merge!(animal_type: params[:animal_type]) if params[:animal_type].present?
 conditions.merge!(rehomed: params[:rehomed]) if params[:rehomed].present?
 conditions.merge!(users: {town: params[:animal_town]}) if params[:animal_town].present?

 @animals = Animal.joins(:user).where(conditions).paginate(:page => params[:new_page], :per_page => 6)

 end

end

Is there a downside to me doing this or should i be creating my query in my model?

Thanks

Upvotes: 0

Views: 103

Answers (1)

j-dexx
j-dexx

Reputation: 10406

This should work.

def rehomed
  @animals = Animal.search(params).paginate(:page => params[:new_page], :per_page => 6)
end

class Animal
  def self.search(params)
    animals = Animal.joins(:user)
    animals = animals.where(animal_type: params[:animal_type]) if params[:animal_type].present?
    animals = animals.where(rehomed: params[:rehomed]) if params[:rehomed].present?
    animals = animals.where(users: {town: params[:animal_town]}) if params[:animal_town].present?
    animals
  end
end

Upvotes: 1

Related Questions