开发者

In Rails models; for symbols get automatically converted to YAML when saving to DB. What is the correct approach?

开发者 https://www.devze.com 2022-12-30 12:59 出处:网络
In my model example Game, has a status column. But I usually set status by using symbols. Example self.status = :active

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 bet开发者_JAVA百科ween 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?


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
0

精彩评论

暂无评论...
验证码 换一张
取 消