2

I have a "Stores" model that contains various locations. Among the attributes for each store is the the "brands" that is carries.

Example: Store1, brands: "Nike, Adidas, Polo"; Store2, brands: "Jcrew, Polo"

I want to be able to select all stores where brand contains "Adidas" (may also contain other brands)

Something along the lines of:

@search = Stores.where(brands: params[:brand]) 

but need it to be

@search = Stores.where(brands.include? params[:brand]) 

which clearly doesn't work

What's the best way to deal with this?

dmt2989
  • 1,610
  • 3
  • 17
  • 30

2 Answers2

2

If brands is a string and params[:brand] contains a single brand name, you can use MySQL's LIKE function:

@search = Stores.where(['BRANDS LIKE ?', "%#{params[:brand]}%"]) 
infused
  • 24,000
  • 13
  • 68
  • 78
-3

You can do this with the following statement.

@search = Stores.where("brands = ?", params[:brand])

A similar example is given in Listing 11.43 of the Hardtl rails tutorial

You should also note that rails models generally are meant to have singular names, i.e. Store instead of Stores.

quilligana
  • 241
  • 2
  • 7