views:

50

answers:

1

In my model example Game, has a status column. But I usually set status by 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 use the above Map to switch between viewable status and viceversa.

However when the data gets saved to db, ActiveRecord appends "--- " to each status. So when I retrieve back the status is screwed.

What should be the correct approach?

+2  A: 

Override the getter and the setter:

def status
  read_attribute(:status).to_sym
end

def status=(new_status)
  write_attribute :status, new_status.to_s
end
neutrino
This worked. Thanks
Ram
Why is this not the default for symbols?
Ram
My guess is that's because if they were serialized as strings, then on deserialization there would be no way to tell what's being deserialized - a string or a symbol.
neutrino