find_by_sql with array format in Rails 3
Asked Answered
F

1

9

good day guys!

I'm using find_by_sql() in rails 3 to fetch records as follows.

@list=Email.find_by_sql(["SELECT * FROM Emails WHERE sent_id=?",params[:id]])

How to modify the same statement if multiple parameter applies for same attribute, say for example :

@list=Email.find_by_sql(["SELECT * FROM Emails WHERE (sent_id=? OR from_id=?)",params[:id],params[:id]])

Here, both sent_id and from_id attributes receives same parameter params[:id]

So, instead of passing same params[:id] twice, is there any mechanism available to pass parameter based on order?

Frontiersman answered 11/6, 2012 at 9:5 Comment(0)
O
20

You can use a hash to name the interpolated values, like this:

@list = Email.find_by_sql(["SELECT * FROM Emails WHERE (sent_id = :id OR from_id = :id)", {:id => params[:id]}])
Ophthalmitis answered 11/6, 2012 at 14:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.