Rails: finding multiple tables from a single query

How to write a condition statement in a method findor paginateso that users can search for names Projectand at the same time Project Category?

Now my code is as follows:

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

So, I also have a table Categorywith a field name. How to combine these two nametogether in this search query?

+3
source share
2 answers

Assuming your model Project 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 :orderabove if / if necessary.

+8
source

I would do:

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

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

0

Source: https://habr.com/ru/post/1704872/


All Articles