railsnewbie
railsnewbie

Reputation: 171

Rails: Use a variable as a hash key

I've been trying to do this for the past 10 hours, but it's been useless.

For example:

Event.where(login_screen: Time.now-8.days ..Time.now)

I have an Event table and login_screen is one of the column names. I'm listing them in a drop-down menu and I'd like to take the event names as a variable. It's in the request params like this: params[:segmentation][:first_event]. When I tried to give it like:

Event.where(params[:segmentation][:first_event] Time.now-8.days ..Time.now)

...it didn't work. I tried to use to_sym but that didn't help either.

How can I use a variable as a symbol?

Another question:

What's the difference between :hello and hello: ?

Upvotes: 3

Views: 1304

Answers (2)

Milind
Milind

Reputation: 5112

these are the different ways to pass arguments in where clause:--

User.where(["name = ? and email = ?", "Joe", "[email protected]"])

User.where(["name = :name and email = :email", { name: "Joe", email: "[email protected]" }])

User.where("name = :name and email = :email", { name: "Joe", email: "[email protected]" })

using hash:-

User.where({ created_at: (Time.now.midnight - 1.day)..Time.now.midnight })

User.where({ name: ["Alice", "Bob"]})

User.where({ name: "Joe", email: "[email protected]" })

Upvotes: 0

mikdiet
mikdiet

Reputation: 10018

It's alternative syntax for ruby hashes with symbols as keys

Event.where(login_screen: Time.now-8.days ..Time.now)

is the same as

Event.where(:login_screen => Time.now-8.days ..Time.now)

So, if you store key in variable you need use 'hash rocket' syntax:

Event.where(params[:segmentation][:first_event] => Time.now-8.days ..Time.now)

Upvotes: 3

Related Questions