0

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.

ricsrock
  • 951
  • 9
  • 13

1 Answers1

3

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.

Leger
  • 1,184
  • 8
  • 7
  • Looks like both of those examples have predictable keys in the hstore column. This app has dynamic, user-defined keys. Please let me know if I'm reading it wrong. – ricsrock Oct 28 '13 at 19:44
  • While this should work, it's not the rails way: http://stackoverflow.com/a/19059398/781704 – Pierre Dec 27 '13 at 09:43