ruby Rails 5.2枚举新用法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby Rails 5.2枚举新用法相关的知识,希望对你有一定的参考价值。

create_table :conversations do |t|
  t.column :status, :integer, default: 0
end

class Conversation < ActiveRecord::Base
  enum status: [ :active, :archived ]
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)

class Conversation < ActiveRecord::Base
  enum status: { active: 0, archived: 1 }
end

Conversation.statuses[:active]    # => 0
Conversation.statuses["archived"] # => 1

Conversation.where("status <> ?", Conversation.statuses[:archived])

class Conversation < ActiveRecord::Base
  enum status: [:active, :archived], _suffix: true
  enum comments_status: [:active, :inactive], _prefix: :comments
end

conversation.active_status!
conversation.archived_status? # => false

conversation.comments_inactive!
conversation.comments_active? # => false

class Conversation < ActiveRecord::Base
  enum status: [:active, :archived], _suffix: :comment
end

conversation.comments_inactive!
conversation.comments_active? # => false

以上是关于ruby Rails 5.2枚举新用法的主要内容,如果未能解决你的问题,请参考以下文章

Rails 5.2 API - 在JSON中返回枚举值

Rails 5.2 不呈现新视图

Rails 5.2 无法使用 Sublime Text 打开 Rails 凭据

使用 Rails 5.2 ActiveStorage 创建和保存 pdf 并稍后附加到电子邮件

如何在 ActiveStorage (Rails 5.2) 中更新附件

在 Rails 5.2 中禁用活动存储