ruby-on-rails - Rails - 选择、加入和排序

标签 ruby-on-rails ruby postgresql join

我正在尝试对我的 Assets 进行排序,以便它们根据用户数量以降序显示。此代码在 Postgres 中有效,但在 Ruby 中似乎无效。不知道哪里出了问题。任何帮助表示赞赏。提前谢谢你。

def order_assets
  @asset = 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

我希望所有黄色的 Assets 都在顶部,当有用户的 Assets 在下面填写时。

Screenshot of Problem

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
GROUP BY assets.id
HAVING count(*) > 0
ORDER BY the_count;

这就是 Postgres 的诞生方式:

Screenshot of Postgres

最佳答案

最终将所有内容都移到了 Assets 模型中。如果有人需要/想要,将在答案代码下发布该代码。

我首先将 assets.id 切换为 assets.*,因为有一个 asset_profile_id 参数没有通过。我包含了 .where 函数,以便查询知道从哪个 asset_profile 获取 assets。我添加的唯一另一件事是对 Assets 进行额外排序,以便根据其 ID 编号对剩余部分进行排序。

def set_assets
  @assets = Asset.select("assets.*, 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: params[:id]).group("assets.id").having("count(*) > 0").order("the_count ASC, assets.id ASC")
end

我最终将代码移到了 Assets 模型中的一个范围内:

scope :ordered_by_user_count, -> (profile_id) { 
  select("assets.*, 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: profile_id)
    .group("assets.id")
    .having("count(*) > 0")
    .order("the_count ASC, assets.id ASC")
}

谢谢你们指引我正确的方向。

关于ruby-on-rails - Rails - 选择、加入和排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26873315/

相关文章:

java - 带有 Spring JDBC 的 Postgres "SKIP LOCKED"

ruby-on-rails - Rails 6 中底层模型更新时如何使 Action Cache 过期?

ruby-on-rails - 使用 Ruby on Rails 创建非标准页面

ruby-on-rails - rails 4 + ReactJS : "SyntaxError: cannot have an implicit value in an implicit object"

ruby - gem 规范失败

ruby-on-rails - 我可以使用 Rails 3.2.3 更新到 Ruby 2.1.2 吗?

Postgresql - 如何授予用户更改表列的权限?

ruby-on-rails - Rails ActiveRecord 似乎忘记了我的 PG 模式

Ruby 停止并移动到 for 循环的下一次迭代

spring - @Query 无法识别 Spring 框架中单引号内的参数