How to store and compare :symbols in an ActiveRecord (Ruby on Rails)

后端 未结 7 1368
梦谈多话
梦谈多话 2021-02-05 04:51

I thought it would be good to populate a status field in an activeRecord table using constants. However, when it comes to checking if this status has a particular status, I\'m h

7条回答
  •  后悔当初
    2021-02-05 05:09

    As of Rails 4.1, Active Record now supports enums

    From the release notes:

    2.5 Active Record enums

    Declare an enum attribute where the values map to integers in the database, but can be queried by name.

    class Conversation < ActiveRecord::Base
      enum status: [ :active, :archived ]
    end
    
    conversation.archived!
    conversation.active? # => false
    conversation.status  # => "archived"
    
    Conversation.archived # => Relation for all archived Conversations
    
    Conversation.statuses # => { "active" => 0, "archived" => 1 }
    

    Additional documentation here: http://api.rubyonrails.org/v4.1.0/classes/ActiveRecord/Enum.html

提交回复
热议问题