Question

I have these relationships:

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

class Answer < ActiveRecord::Base
  belongs_to :applicant
end

The answer model has an hstore attribute called properties. The properties hash will have dynamic keys as they are created in the app by the user.

I can't seem to successfully whitelist these dynamic keys within the applicants controller.

This is my current (unsuccessful) attempt.

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

Thanks for any help.

Was it helpful?

Solution

UPD. Try to use following approach (tested in separate file):

@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. There is pretty good article on working with hstores. And some general things on using hstore in Rails 4.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top