我有一个LibraryEntry
模型,其字符串列status
属于User
模型。
我想找到属于LibraryEntry
的所有User
模型,我可以在其中设置字符串列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
可以是
watch
complete
drop
backlog
wishlist
答案 0 :(得分:3)
您正在加入另一个表(用户),该表也有一个名为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片段时,这总是一种很好的做法。