totocaster
totocaster

Reputation: 6363

Rails: Searching multiple tables from one query

How do I write condition statement in find or paginate method to allow users search in Project and Project Category names simultaneously?

Now my code looks like this

@projects = Project.paginate :per_page => 20, :page => params[:page], :conditions => ['name LIKE ?', "%#{params[:search]}%"]

So I have also Category table with name field. How do I combine those two names together in this search query?

Upvotes: 3

Views: 5813

Answers (2)

vladr
vladr

Reputation: 66661

Assuming that your Project model has_many :categories:

@projects = Project.paginate :per_page => 20, :page => params[:page], :joins => :categories, :conditions => ['projects.name LIKE ? OR categories.name LIKE ?', "%#{params[:search]}%", "%#{params[:search]}%"], :order => 'projects.id DESC'

Change the :order above if/as needed.

Upvotes: 8

Chry Cheng
Chry Cheng

Reputation: 3468

I would do:

@categories = Category.find :conditions => ["name like ?", "%#{params[:search]}%"]

Concatenate @projects and @categories, and then use the result as the final search result list.

Upvotes: 0

Related Questions