Rails,如何通过实例数组

时间:2015-09-15 21:12:29

标签: ruby-on-rails ruby sorting activerecord rails-activerecord

在Ruby on Rails应用程序中,我有一个名为Members的类,每个对象都有一个名为执行位置的属性,它是此数组中的一个字符串

@executive = ['President', 'Vice President', 'Treasurer', 'Secretary', 'Director of Programs', 'Director of Strategic Partnerships', 'Director of Public Relations', 'Director of Publications', 'Director of Community Service', 'Director of Fundraising', 'Historian', 'Digital Administrator']

我想按照这个顺序对它们进行排序,首先是总统,然后是副总统等等。

Member.all.sort_by {|member| member.executive_position == @executive}

3 个答案:

答案 0 :(得分:2)

val itA: Iterator[A] = // ...
val itB: Iterator[B] = itA.flatMap(a => a match {
  case b: B => Iterator(b)
  case c: C => parse(c)
})

答案 1 :(得分:0)

Member.all.sort_by { |member| @executive.index(member.executive_position) }

如果在其他地方使用它,我会继续在Member模型中添加一个方法,如下所示:

# member.rb
class Member < ActiveRecord::Base
  ...
  EXECUTIVES = ['President', 'Vice President', 'Treasurer',
    'Secretary', 'Director of Programs', 'Director of Strategic Partnerships', 
    'Director of Public Relations', 'Director of Publications', 
    'Director of Community Service', 'Director of Fundraising', 
    'Historian', 'Digital Administrator']

  def position
    EXECUTIVES.index(executive_position)
  end

end

然后代码将

Member.all.sort_by { |member| member.position }

或更短

Member.all.sort_by(&:position)

答案 2 :(得分:0)

我认为你的逻辑错误。您应该使用SQL CASE语句在数据库内进行排序,这样可以更容易地将此​​排序与其他查询组件(例如子查询和辅助排序键)结合使用。例如,你可以有这样的常量:

EXECUTIVES = [ 'President', ... ]

然后在你的模型中使用这样的范围:

def self.order_by_rank
  q = connection.method(:quote)
  order([
    'case members.executive_position',
    *EXECUTIVES.length.each_with_index.map { |s, i| "when #{q[s]} then #{i}" },
    "else #{EXECUTIVES.length}",
    'end'
  ].join(' '))
end

你可以这样说:

Member.order_by_rank
Member.where(...).order_by_rank.order(:name)

order_by_rank范围的直接修改会为您提供in_this_order('President', 'Vice President', 'Treasurer', ...)范围:

def self.in_this_order(*titles)
  q = connection.method(:quote)
  order([
    'case members.executive_position',
    *titles.each_with_index.map { |s, i| "when #{q[s]} then #{i}" },
    "else #{titles.length}",
    'end'
  ].join(' '))
end

您还可以将标题及其顺序放在数据库表中:

title            | pos
-----------------+----
'President'      | 1
'Vice President' | 2
...

然后加入它和ORDER BY pos