12

我有一个eventsstate列的表。如果一切按计划进行,则状态只能是以下之一:

  • scheduled
  • invited
  • notified
  • started
  • ended

是否可以按顺序排序state并指定哪个值排在第一位、第二位、第三位等...?

奖励积分:有没有办法在 Rails 3 中轻松做到这一点?

4

1 回答 1

29

1.如果你只需要postgres中的sql,这里是:

select * from events
order by (case state 
          when 'scheduled' then 1
          when 'notified' then 2
          when 'invited' then 3
          when 'started' then 4
          when 'ended' then 5 
          end)    

您可以更改 sql 中的状态顺序,无需更改 ruby​​ 代码,玩 sql fiddle:http ://sqlfiddle.com/#!12/976e9/3 。

2.在mu的建议中,你可以使用枚举类型,这样效率更高,如果需要更改顺序,可以重新创建枚举。看到这个 sql 小提琴:http ://sqlfiddle.com/#!12/f6f3d/2

CREATE TYPE states AS ENUM ('invited', 'scheduled', 'notified', 'started', 'ended');
create table events(
  name varchar(100),
  state states
);

select * from events order by state;

3.在纯红宝石的方式,你可以定义一个哈希:

test_hash = {'scheduled'=>1, 'notified'=>2, 'invited'=>3, 'started'=>4, 'ended'=>5}
Events.all.sort! {|x, y| test_hash[x.state] <=> test_hash[y.state]}

4.但在我看来,您应该添加一个名为“states”的表,其中包含“name”和“sequence”列,并在“sequence”中指定顺序。然后加入“事件”和“状态”。更改订单时,无需更改代码。

于 2013-09-06T03:29:06.583 回答