Ask A Question

Notifications

You’re not receiving notifications from this thread.

Multi select form & DB search

Sascha M. asked in General

Hi there,

I want to allow a user to select multiple brands and teams in a select form field. I am using the user's input to create CSV through running a query.

So far I only can query single teams and brands:

 ...
Order.where("created_at between (?) and (?) and brand = ? and team = ?", self.start, self.end, self.brand, self.team).each do |order|
 ...

Do you know how to solve this?

Reply

Hey Sacha,

For those, you actually want to querying using IN so that SQL can look for matches in an array of IDs. For example:

brand_ids = [1,2,3] # These IDs may come from your form params from a multi-select
Order.where(brand_id: brands)
# SELECT "orders".* FROM "orders" WHERE "orders"."brand_id" IN (1, 2, 3)

And remember you can chain your where calls to make it cleaner:

Order.where("created_at between (?) and (?)", self.start, self.end).where(brand: self.brand,  team: self.team)
Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 86,946+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.