如何创建活动记录联接查询

问题描述 投票:1回答:1

我正在使用Sinatra和Heroku托管的PostgreSQL数据库。我有一个在续集中有效的查询:

@shortmembers = DB[:shortlists].distinct(:shortname).join(:shortmembers, :short_id => :listid) 

我将如何在Active Record中执行此操作?

在SQL中为:

SELECT DISTINCT(shortname), listid FROM shortlists INNER JOIN shortmembers ON shortlists.listid = shortmembers.short_id

而且,我可以使用Active Record进行原始SQL查询吗?如果是这样,怎么办?

ruby activerecord sinatra sequel
1个回答
0
投票

使用记录在select上的ActiveRecord的joinsActive Record Query Interface,您可以执行like

Shortlists.select(:shortname).uniq.joins(:shortmembers, :short_id => :list_id)

是的,您当然可以使用Active Record进行原始SQL查询,但是您会发现Active Record提供了一种用于大多数查询用例的方法,并且这些方法比原始SQL更可取。

© www.soinside.com 2019 - 2024. All rights reserved.