有没有办法在Rails中将参数传递给Postgres原始查询? [英] Is there a way to pass params to postgres raw query in rails?

查看:73
本文介绍了有没有办法在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"}>, ...]

这篇关于有没有办法在Rails中将参数传递给Postgres原始查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆