Rails按字符串列值通过连接排序

时间:2016-05-29 17:05:11

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

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

1 个答案:

答案 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片段时,这总是一种很好的做法。