ruby-on-rails - Rails 通过连接按字符串列值排序

标签 ruby-on-rails postgresql ruby-on-rails-4 activerecord

我有一个 LibraryEntry 模型,其中一个字符串列 status 属于 User 模型。

我想找到属于 User 的所有 LibraryEntry 模型,我可以在其中为字符串列 status 的值设置优先级对模型进行排序。

例如按字符串列 status 对模型进行排序:[watch,complete,drop,backlog,wishlist]

我已经检查了这个线程 Postgres: Order by string column with known values并尝试编写我自己的 SQL 语句但没有成功,出现错误 PG::AmbiguousColumn: ERROR: column reference "status"is ambiguous

#This is under the model LibraryEntry`
 def self.priority_order
    order("CASE
      WHEN status = 'watch' THEN '1'
      WHEN status = 'complete' THEN '2'
      WHEN status = 'wishlist' THEN '3'
      WHEN status = 'drop' THEN '4'
      WHEN status = 'backlog' THEN '5'
    END")
  end
 #The query to sort the model in the controller
 @lib = @user.library_entries.priority_order.joins(:vn).order('vns.name')

status 可以是

  • 观看

  • 完成

  • 放下

  • 积压
  • 心愿单

最佳答案

您正在加入另一个表(用户),该表也有一个名为 status 的列。

在您的订单中,以 LibraryEntry 表的名称作为前缀。

据推测:

def self.priority_order
  order("CASE
    WHEN library_entries.status = 'watch' THEN '1'
    WHEN library_entries.status = 'complete' THEN '2'
    WHEN library_entries.status = 'wishlist' THEN '3'
    WHEN library_entries.status = 'drop' THEN '4'
    WHEN library_entries.status = 'backlog' THEN '5'
  END")
end

……或者……

def self.priority_order
  order("CASE library_entries.status
    WHEN 'watch'    THEN '1'
    WHEN 'complete' THEN '2'
    WHEN 'wishlist' THEN '3'
    WHEN 'drop'     THEN '4'
    WHEN 'backlog'  THEN '5'
  END")
end

在 Rails 代码中包含 SQL 片段时,这始终是一个很好的做法。

关于ruby-on-rails - Rails 通过连接按字符串列值排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37512650/

相关文章:

ruby-on-rails - Rails 4.1枚举引发错误,而是将对象设置为无效

sql - 计算Postgres中最近的工作日

postgresql物化 View 自己刷新

python - 修复列 "date_of_birth"中的空值违反了非空约束

ruby-on-rails - 带有 MailCatcher 和 Devise gem 的 Rails 4

ruby-on-rails-4 - EventSource 调用 ActionController::Live 挂起

ruby-on-rails - 选择具有外键的关联模型

ruby-on-rails - 向大量收件人发送电子邮件的最佳实践 (Rails + SendGrid)

mysql - 在 Rails 中创建新对象时出错

ruby-on-rails - 我可以使用 Selenium IDE 生成 Cucumber/Capybara 步骤吗?