What relationship with rails am I looking for here?

I have several models that I want to find so that the results can include the results of all models. Let's say I want to search for β€œboots,” and I want it to return the category of boots, as well as the retailers who sell the boots, as well as the actual boots. I have a model for categories, suppliers, and also products.

I would prefer not to create connection tables in this case, because each object requires joining, and this is not necessary because all objects must be included in the search.

I think about using the ransack gem, but I don’t think it is important for the question, because it would be the same regardless of my search procedure.

Maybe a complex relationship makes sense, but I can't wrap it around.

+3
source share
2 answers

Suppose your Product belongs_toa Vendorand belongs_toa Categoryare your request here:

string_to_search = 'boots'
@products = Product.where("title LIKE ?", "%#{string_to_search}%").includes(:vendor, :category).all

He will receive all products with the required header content along with all their categories and suppliers. You can go through the resulting data without additional queries to select a category / supplier for a particular product.

If you need to, say, extract a list of suppliers from @products- just use:

@vendors = @products.map &:vendor
+1
source

, UNION SQL-, . ActiveModel, , ActiveRecord.

0

All Articles