【问题标题】:How to create an Active Record join query如何创建 Active Record 连接查询
【发布时间】:2013-06-02 12:15:41
【问题描述】:

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

@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】:

    使用 ActiveRecord 的 selectjoins,记录在 Active Record Query Interface,你可以做一些事情

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

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

    【讨论】:

    • 感谢您的建议,恐怕这行不通。错误消息说关系“shortmembers”不存在,但它确实存在 - 至少在数据库中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-01
    • 2020-05-16
    相关资源
    最近更新 更多