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

后端 未结 7 1447
梦谈多话
梦谈多话 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:16

    With Rails 4.1.0, you'd probably want to use Active Record enums.

    To quote the official release notes:

    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 }
    

提交回复
热议问题