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

孤街醉人 提交于 2019-12-10 11:29:11

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/2817145/in-rails-models-for-symbols-get-automatically-converted-to-yaml-when-saving-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!