我正在使用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查询吗?如果是这样,怎么办?
使用记录在select
上的ActiveRecord的joins
和Active Record Query Interface,您可以执行like:
Shortlists.select(:shortname).uniq.joins(:shortmembers, :short_id => :list_id)
是的,您当然可以使用Active Record进行原始SQL查询,但是您会发现Active Record提供了一种用于大多数查询用例的方法,并且这些方法比原始SQL更可取。