bsc*_*fer 8 postgresql ruby-on-rails
我有一个events带有state列的表.如果一切按计划进行,州只能是以下之一:
scheduledinvitednotifiedstartedended是否可以按顺序排列state并指定哪个值来自第一,第二,第三等......?
奖励积分:有没有办法在Rails 3中轻松完成这项工作?
Big*_*ang 15
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)
Run Code Online (Sandbox Code Playgroud)
你可以改变sql中的状态顺序,不需要改变ruby代码,播放sql小提琴: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;
Run Code Online (Sandbox Code Playgroud)
3.以纯ruby方式,您可以定义哈希:
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]}
Run Code Online (Sandbox Code Playgroud)
4.但是在我看来,你应该添加一个名为"states"的表,其中包含"name"和"sequence"列,并在"sequence"中指定顺序.然后加入"事件"和"状态".更改顺序时,无需更改代码.
| 归档时间: |
|
| 查看次数: |
2983 次 |
| 最近记录: |