将SQL查询转换为Active Record

时间:2016-04-08 21:31:53

标签: ruby ruby-on-rails-4 rails-activerecord

我需要使用以下命令在Ruby on Rails中查询我的数据库:

select p.name from shoppe_products p
join shoppe_product_categorizations ca on (p.id = ca.product_id)
join shoppe_product_categories c on (c.id = ca.product_category_id)
where c.id = 2

我使用Ruby v 2.1.5,Rails v 4和PG 9.4。

1 个答案:

答案 0 :(得分:0)

您只需执行sql:

即可
query_id = ActiveRecord::Base.connection.quote(id_param)
results = ActiveRecord::Base.connection.exec_query(
  "select p.name from shoppe_products p
  join shoppe_product_categorizations ca on (p.id = ca.product_id)
  join shoppe_product_categories c on (c.id = ca.product_category_id)
  where c.id = #{query_id}"
)

不知道你的模型等,这是我能猜到的最好的解决方案。