我有一个 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/