RoR:PSQL到ruby - .join

时间:2014-11-10 15:28:36

标签: ruby-on-rails ruby postgresql join psql

我意识到这是一个基本的问题,但我在一堵墙上似乎无法过去。我有一个朋友帮我写了这个Postgres代码,现在我想把它转换成ruby,我老实说不知道怎么做。我似乎找不到任何关于如何正确订购所有请求的文档。

Postgres的:

SELECT
        assets.id,
        count(assets_users.asset_id) as the_count
FROM assets
LEFT OUTER JOIN assets_users ON assets.id = assets_users.asset_id
WHERE asset_profile_id = 7
GROUP BY assets.id
HAVING count(*) > 0
ORDER BY the_count;

红宝石:

def order_assets
  @order = Asset.select("assets.id").count("assets_users.asset_id").joins("LEFT OUTER JOIN assets_users ON assets.id = assets_users.asset_id").group("assets.id").having("count(*) > 0").order("assets_users.asset_id")
end

编辑:

新的Ruby代码:

def order_assets
  @order = Asset.select("assets.id, count('assets_users.asset_id) as the_count")
                .joins("LEFT OUTER JOIN assets_users ON assets.id = assets_users.asset_id")
                .group("assets.id")
                .having("count(*) > 0").order("the_count")
end

我希望所有黄色资产都位于顶部,当用户填写在下方时。

Screenshot of Problem

1 个答案:

答案 0 :(得分:2)

以下是等效代码: -

@order = Asset.select("assets.id, count(assets_users.asset_id) as the_count")
              .joins("LEFT OUTER JOIN assets_users ON assets.id = assets_users.asset_id")
              .where("asset_profile_id = ?", current_asset_profile_id)
              .group("assets.id")
              .having("count(*) > 0")
              .order("the_count")