0

동적 hstore 키를 화이트리스트 :내가 이러한 관계를 어떻게 중첩 된 모델

class Applicant < ActiveRecord::Base 
    has_many :answers 
    accepts_nested_attributes_for :answers 
end 

class Answer < ActiveRecord::Base 
    belongs_to :applicant 
end 

대답 모델은 속성이라는 hstore의 속성이 있습니다. 속성 해시는 사용자가 앱에서 만든 동적 키를 갖습니다.

신청자 컨트롤러에서 이러한 동적 키를 성공적으로 허용 목록에 등록 할 수 없습니다.

이것은 현재 나의 (실패한) 시도입니다.

def applicant_params 
    params.require(:applicant).permit(:answers_attributes: [:question_id, :id]).tap do |whitelisted| 
     whitelisted[:answers_attributes][:properties] = params[:applicant][:answers_attributes][:properties] 
    end 
end 

도움 주셔서 감사합니다.

답변

3

UPD. (별도의 파일에 테스트) 방식 다음 사용해보십시오 :

@params = ActionController::Parameters.new(
    applicant: {answers_attributes: { 
       "0" => {question_id: 10, id: 110, properties: {a: "b", c: "d"}}, 
       "1" => {question_id: 20, id: 120, properties: {m: "n", o: "p"}} 
}}) 

def applicant_params 
    #properties should be [:a, :c, :m, :o] 
    properties = [] 
    @params[:applicant][:answers_attributes].values.each do |answer| 
    properties |= answer[:properties].keys 
    end 
    @params.require(:applicant).permit(answers_attributes: 
             [:question_id, :id, properties: properties]) 
end 

BTL합니다. hstores 작업에 꽤 좋은 article가 있습니다. 그리고 hstore in Rails 4을 사용할 때의 일반적인 것들.

+0

두 예제 모두 hstore 열에 예측 가능한 키가있는 것 같습니다. 이 앱에는 동적 인 사용자 정의 키가 있습니다. 제가 잘못 읽었다면 알려주세요. – ricsrock

+0

네 말이 맞아. 내 맞춤 솔루션과 함께 제공 – Leger

+0

대단히 감사합니다! – ricsrock