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

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

    This is kind of late, but may help someone else.

    If you have classes with different statuses, you might consider an approach using constants along with scopes like this:

    class Account < ActiveRecord::Base
      #-------------------------------------------------------------------------------
      # Configuration
      #-------------------------------------------------------------------------------
    
      # STATUS is used to denote what state the account is in.
      STATUS = { :active => 1, :suspended => 2, :closed => 3 }
    
      # Scopes
      scope :active, where(:status => Account::STATUS[:active])
      scope :suspended, where(:status => Account::STATUS[:suspended])
      scope :closed, where(:status => Account::STATUS[:closed])
      ...
    end
    

    Then you can easily find records based on status, like so:

    # get all active accounts
    active_accounts = Consumer.active.all
    # get 50 suspended accounts
    suspended_accounts = Consumer.suspended.limit(50)
    # get accounts that are closed and [some search criteria]
    closed_accounts = Consumer.closed.where([some search criteria])
    

    Hope this helps someone else!

    EDIT: If you're more into using gems, the simple_enum gem looks like an excellent alternative.

提交回复
热议问题