SQL IN – Do it in Rails find using an array

I thought this was pretty cool and a little more elegant than using a string, which I have been doing before I saw this. In SQL you can do a command like so:

SELECT * FROM widgets WHERE id IN (1,2,3,4,5);

I was doing this before:

Widget.find(:all,:conditions=>”id in (1,2,3,4,5)”)

Instead of doing this you can use an array instead of a string:

Widget.find(:all,:conditions=> {:id => [1,2,3,4,5])

That looks better.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.