데이터가 직렬화 된 모델이 있으며 best_in_place
보석을 사용하여이 데이터를 편집하고 싶습니다. best_in_place gem을 사용할 때 기본적으로 불가능합니다. 어떻게 할 수 있습니까?best_in_place gem을 사용하여 직렬화 된 데이터를 변경하려면 어떻게해야합니까?
1
A
답변
4
method_missing
및 respond_to_missing?
을 확장하여 요청을 직렬화 된 데이터로 전달함으로써 수행 할 수 있습니다. 일련 번호 Hash
이 data
에 있다고 가정 해 보겠습니다. 당신은 예를 들어,이 코드를 사용하여 직렬화 된 데이터를 포함하는 것 클래스에서 : [: 이름] 세터 object.data_name를 사용하여 게터의 object.data_name 및 설정 값을 사용하여
def method_missing(method_name, *arguments, &block) # forewards the arguments to the correct methods
if method_name.to_s =~ /data_(.+)\=/
key = method_name.to_s.match(/data_(.+)=/)[1]
self.send('data_setter=', key, arguments.first)
elsif method_name.to_s =~ /data_(.+)/
key = method_name.to_s.match(/data_(.+)/)[1]
self.send('data_getter', column_number)
else
super
end
end
def respond_to_missing?(method_name, include_private = false) # prevents giving UndefinedMethod error
method_name.to_s.start_with?('data_') || super
end
def data_getter(key)
self.data[key.to_i] if self.data.kind_of?(Array)
self.data[key.to_sym] if self.data.kind_of?(Hash)
end
def data_setter(key, value)
self.data[key.to_i] = value if self.data.kind_of?(Array)
self.data[key.to_sym] = value if self.data.kind_of?(Hash)
value # the method returns value because best_in_place sets the returned value as text
end
은 이제 object.data에 액세스 할 수 있습니다 = "테스트". 그러나 best_in_place
을 사용하여이 작업을 수행하려면 attr_accessible
목록에 동적으로 추가해야합니다.
def accessable_methods # returns a list of all the methods that are responded dynamicly
self.data.keys.map{|x| "data_#{x.to_s}".to_sym }
end
private
def mass_assignment_authorizer(user) # adds the list to the accessible list.
super + self.accessable_methods
end
그래서보기에 지금 호출 할 수 있습니다 :이 작업을 수행하려면 당신은 mass_assignment_authorizer
의 동작을 변경하고 객체는 다음과 같이 편집 할 수 있어야 메소드 이름의 배열 accessable_methods
에 응답해야
best_in_place @object, :data_name
은의 직렬화 된 데이터를 편집하려면 @ object.data [: 이름]
// 당신은 대신 속성 이름의 요소 인덱스를 사용하여 배열에 대해이 작업을 수행 할 수 있습니다
<% @object.data.count.times do |index| %>
<%= best_in_place @object, "data_#{index}".to_sym %>
<% end %>
나머지 코드는 변경하지 않아도됩니다.
고맙습니다. 비 연관 Array/Hash는 어떨까요? 키가없는 배열과 비슷한 것을 가질 수 있습니까? 여기에 내 문제가있다 : http://stackoverflow.com/questions/28415176/how-to-edit-a-serialized-array-with-unknown-keys 고마워! –
편집을 참조하십시오 배열에 대한 사용 방법에 extnsion 추가 – davidb
나는 또한 해시 및 배열을 모두 처리 할 다른 소스를 편집했습니다 .... – davidb