瞎扯淡 期待 Rails enum 的新功能

joezhang · December 16, 2015 · Last by gihnius replied at December 18, 2015 · 2608 hits
class Conversation < ActiveRecord::Base
  enum status: [ :active, :archived ]
end

Of course, you can also query them directly if the scopes don't fit your needs:

Conversation.where(status: [:active, :archived])
Conversation.where.not(status: :active)

太需要这个 enum 功能了,不知道什么时候才能从 edge 更新到 Rails 新版本! 请教目前(Rails4.2.5)有什么简单而且高效的方法能实现以上功能,谢谢!

已经有了,但是还不能用 symbol 作为查询条件

http://api.rubyonrails.org/v4.2/classes/ActiveRecord/Enum.html

是的,稍微麻烦一点:

Conversation.where(status: [ Conversation.statuses[:active], Conversation.statuses[:archived] ])
Conversation.where.not(status: Conversation.statuses[:active])

可以做scope

stages = %w(active archived)

stages.each do |s|
  scope s, -> { where stage: s}

  define_method :"#{s}?" do
    self.stage == s
 end

  define_method :"#{s}!" do
    self.stage = s
    self.save
  end
end

类似这样?

@rei @geekontheway 就是想用 symbol 作为查询条件,现在写一个应用,User has_one Profile, Profile 中有个 enum 字段,其中有个查询功能,要根据多选的 enum 字段查找 User,如果能用 Conversation.where(status: [:active, :archived]) 的话就简单多了。

感觉 rails 的 enum 只是封装了一下 hash 实际并不太好用,ruby core 里面何时才能加个 enum 的类型

使用@zhang_soledad 提到的enumerize

好像还不能加 prefix, 还得用 Enumerize

You need to Sign in before reply, if you don't have an account, please Sign up first.