In Rails models; for symbols is automatically converted to YAML when saved to the database. What's the correct approach?

In my example Game model, there is a status column. But I usually set the status using symbols. Example

self.status =: active
    MATCH_STATUS = { 
      :betting_on => "Betting is on",
      :home_team_won => "Home team has won",
      :visiting_team_won => "Visiting team has one",
      :game_tie => "Game is tied"
    }.freeze

def viewable_status
  MATCH_STATUS[self.status]
end

      

I am using the above map to switch between visible status and vice versa.

However, when the data is saved to db, ActiveRecord adds "---" to each status. So when I go back, the status is screwed up.

What should be the correct approach?

+2


a source to share


1 answer


Reverse getter and setter:



def status
  read_attribute(:status).to_sym
end

def status=(new_status)
  write_attribute :status, new_status.to_s
end

      

+3


a source







All Articles