问题
I have a complex raw query where I want to pass params instead of interpolating them
Ex:
query =
"SELECT id, abbr as code, name
FROM states
WHERE name IN ('#{params[:state].join("','")}')"
ActiveRecord::Base.connection.execute(query)
Is there any way to pass params like the ActiveRecord does
State.where(name: ['Alabama', 'Alaska'])
回答1:
Try find_by_sql:
Post.find_by_sql(["SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date])
[#<Post:0x36bff9c @attributes={"title"=>"The Cheap Man Buys Twice"}>, ...]
来源:https://stackoverflow.com/questions/38975247/is-there-a-way-to-pass-params-to-postgres-raw-query-in-rails