首页 > 代码库 > ruby on rails 在model中使用enum的注意事项

ruby on rails 在model中使用enum的注意事项

enum的作用是声名一个枚举属性来映射数据库里整型字段的值,并能通过这个属性来查询数据库。

可以这么使用(事例来自官方),比如:

class Conversation < ActiveRecord::Base
  enum status: [ :active, :archived ]
end
或者
class Conversation < ActiveRecord::Base enum status: { active: 0, archived: 1 } end
# conversation.update! status: 0
conversation.active!
conversation.active? # => true
conversation.status  # => "active"

# conversation.update! status: 1
conversation.archived!
conversation.archived? # => true
conversation.status    # => "archived"

# conversation.status = 1
conversation.status = "archived"

conversation.status = nil
conversation.status.nil? # => true
conversation.status      # => nil

关于查询的:
Conversation.where(status: [:active, :archived]) Conversation.where.not(status: :active)

这样使用很方便,但是使用这个enum时候一定要非常注意,你可能注意到了,它会产生一些方法。比如上面,它产生了:active!active?status= 等等。

如果你一不小心使用了:group属性,比如这样定义:

class Conversation < ActiveRecord::Base
  enum status: {group: 0, single: 1}
end

运行时它会产生You tried to define an enum named "statuss" on the model "ConfirmAsset", but this will generate a class method "group", which is already defined by Active Record.这样的错误。

另外使用字段名称的时候也要注意,因为我得到了这样的错误:You tried to define an enum named "import" on the model "ConfirmAsset", but this will generate a instance method "import=", which is already defined by another enum.

 

ruby on rails 在model中使用enum的注意事项