8

How to pass parameters sql query in find by sql

2 Answers 2

33

The documentation explains it all. You do it like this, where author_id and start_date are the parameters passed in.

Post.find_by_sql ["SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date]

http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-c-find_by_sql

Sign up to request clarification or add additional context in comments.

1 Comment

The fact that the parameterized SQL and the parameters themselves need to be put in an array was what helped me, here. I was trying to pass them to find_by_sql as 2 separate params.
-2

There are several different ways of doing this

one way would be what Brendan has proposed.

for others I'll take Brendan's example itself

2 - Post.find(:all, :conditions => "author=#{author_id} and created=#{start_date}")

3 - Post.find_all_by_author_id_and_created(author_id, start_date)

and If you are using rails 3 even you can build your query

http://m.onkey.org/2010/1/22/active-record-query-interface

cheers

sameera

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.