2013-03-21 3 views
0

데이터베이스에 실제 열이 하나있는 모델이 있습니다. 이 열은 구성의 JSON 문자열로 저장됩니다. 이 구성 JSON 속성 내부에 매핑하려는 가상 속성을 사용합니다. 기본적으로 DB에 묶음 열을 만들고 싶지 않지만이 JSON 특성을 사용하여 모든 것을 포함합니다. 이것보다 더 깨끗한 방법이 있습니까 def?가상 속성을 해시에 포함시키는 것

class Device < ActiveRecord::Base 
    attr_accessible :configuration 
    serialize :configuration, JSON 

    attr_accessor :background_color, :title 

    # below is ew 
    def background_color; self.configuration["background_color"]; end 
    def background_color=(value); self.configuration["background_color"] = value; end 

    def title; self.configuration["title"]; end 
    def title=(value); self.configuration["title"] = value; end 
end 

이상적으로는 attr_maps_to_hash :configuration, [:background_color, :title]과 같은 것을 찾고있을 것입니다. 이 같은 것이 존재합니까?

+0

또 다른 해결 방법은 getters와 setters를 생성하기 위해 속성 기호 배열에'class_eval'을 사용하는 것입니다.하지만 그 역시 추악합니다. – Larry

답변

1

이 경우 ActiveRecord::Store을 사용할 수 있습니다.

class User < ActiveRecord::Base 
    store :settings, accessors: [ :color, :homepage ] 
end 

u = User.new(color: 'black', homepage: '37signals.com') 
u.color       # Accessor stored attribute 
u.settings[:country] = 'Denmark' # Any attribute, even if not specified with an accessor 

# Add additional accessors to an existing store through store_accessor 
class SuperUser < User 
    store_accessor :settings, :privileges, :servants 
end 

PostgreSQL을 사용하는 경우 HStore을 확인하십시오.

+0

좋습니다. 문제는 ActiveRecord :: Store가 이들을 'attr_accessible'로 선언하지 않기 때문에 "ActiveModel :: MassAssignmentSecurity :: Error : 보호 속성을 대량 할당 할 수 없습니다 : background_color, title"입니다. 일부 속성에 액세스 할 수 없기를 바랄 수도 있기 때문에 예상됩니다. 그러나 나는 이것이 같은 배열 (또는'attr_accessible'과'store_accessor' 둘 다에 사용 된 배열을 가진 var)을 가지고 분리 된'attr_accessible' 라인을 가질 필요가 있음을 의미합니다. – Larry

0

두 가지 방법이 떠오릅니다.

먼저, define_method를 호출하는 동안 속성 [: background_color, : title]의 배열을 가져 와서 반복 할 수 있습니다. define (method_name)과 define ("# {method_name} =")의 두 가지 메소드를 정의하게됩니다.

둘째, 비슷한 생각이지만 누락 된 방법을 사용합니다. 키 - 값 저장에 내장 한 3.2로

def method_missing(method_name, *args, &block) 
    ...see if it's a get or set... 
    ...do your stuff... 
    ...rain dance... 
    ...yay... 
end 
관련 문제