Is there a way to pass params to postgres raw query in rails?

走远了吗. 提交于 2019-12-08 13:25:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!