有没有办法在Rails中将参数传递给Postgres原始查询?
问题描述:
我有一个 complex 原始查询,我想在其中传递参数而不是对参数进行插值
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)
有没有办法像ActiveRecord那样传递参数
Is there any way to pass params like the ActiveRecord does
State.where(name: ['Alabama', 'Alaska'])
答
尝试 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"}>, ...]