2013-05-07 2 views
1

제 모델의 문자열 필드 (short)가 인 db에 저장합니다. 하지만 나는 항상 으로 돌아 가기를 원합니다.은 문자열 대신 기호이고, 또한이 문자열 특성에 기호를 할당하고 싶습니다. 지금 내가하고있는 일은 효과가 없습니다.모델 특성을 기호로 처리하십시오.

class MyModel < ActiveRecord::Base 
    attr_accessible :attr1 

    def attr1 
    # self.try(:attr1).to_sym # how to return symbol? 
    end 

    def attr1= value 
    # super.attr1.to_sym # doesn't work either 
    end 
end 

어떻게 전달합니까?

+0

어떤 종류 o f 데이터가 열 저장소를 사용합니까? – muttonlamb

+0

짧은 문자열 값 –

+0

왜 기호에 특성을 지정 하시겠습니까? 데이터베이스는 그것을 기호로 저장하지 않습니다. –

답변

5

필자는 getter 만 덮어 써야한다고 생각합니다. 세터는 필드 인 경우 잘 작동합니다.

class MyModel < ActiveRecord::Base 
    def attr1 
    self.attributes['attr1'].to_sym 
    end 
end 

또는 당신은 또한 시리얼 만들 수 있습니다

class SymbolSerializer 
    def self.dump(obj) 
    return unless obj 
    obj.to_s 
    end 

    def self.load(text) 
    return unless text 
    text.to_sym 
    end 
end 

과 다음 모델 :

class MyModel < ActiveRecord::Base 
    serialize :attr1, SymbolSerializer 
end 
+0

어떨까요? –

+0

@MariusKavansky DB에는 기호 개념이 없으므로 값은 문자열로 저장됩니다. 문자열은 읽은 후에 심볼로 변환됩니다. –

+0

속성이 nil 일 때 시나리오를 설명하기 위해 작은 개선점을 하나 더 추가합니다.'self.attributes [ 'attr1']. try (: to_sym)' – Renra

0

여러 열 또는 다른 모델에 그것을 할 필요가 있다면 나는 것 해결책을 일반화 할 것을 제안하십시오 :

class MyModel < ActiveRecord::Base 
    include Concerns::Columnable 

    treat_as_symbols :attr1 
end 

module Concerns::Columnable 
    extend ActiveSupport::Concern 

    included do 
    def self.treat_as_symbols *args 
     args.each do |column| 
     define_method "#{column}" do 
      read_attribute(column.to_sym).to_sym 
     end 
     end 
    end 
    end 
end 
관련 문제