5

I have a need to use the internal mechanism rails uses to convert a string into a parameter hash suitable for creating an object build with nested attributes. I can't find where in the life cycle of the request rails actually prepares the params[] hash.

The string looks like:

"foo[butter]=fat&foo[cheese]=cheddar&bar[fork]=pointy&bar[knife]=sharp"

Just to give some context the above string is extracted from an encrypted request via an API call to my app. Which is why it's in that form once decrypted.e.g.

def create
  decrypted = decrypt(params[:q])
  Object.create(magically_convert_to_param_hash(decrypted))
end

I realise I can manually parse this string and convert it into the required hash but it seems a little wet considering code exists in the framework that already does it.

0

2 Answers 2

12

As of Rails 4 you can do this as well:

  raw_parameters = { 
    :foo => {
      :butter => "fat", 
      :cheese => "cheddar", 
    },
    :bar => {
      :fork => "pointy",
      :knife => "sharp",
    }
  }

  params = ActionController::Parameters.new(raw_parameters)

then you can require and permit like so

  params.require(:foo).permit(:butter, :cheese)
  params.require(:bar).permit(:fork, :knife)
Sign up to request clarification or add additional context in comments.

Comments

6

Use CGI::parse like this:

params_in_url = "foo[butter]=fat&foo[cheese]=cheddar&bar[fork]=pointy&bar[knife]=sharp"
params_hash = CGI::parse(params_in_url)

Or use Rack::Utils.parse_query:

params_hash = Rack::Utils.parse_query(params_in_url)

4 Comments

Thanks for that, I've tried that and the parse_nested_query as well but it doesn't work - It does create a hash but pass that to the new or create method of an object and it won't create the nested object. The structure of the hash for nested objects should have an attributes_for_<nested model> in it.
Ok - I was missing the point, it is easy to forget that the "accepts_nested_attributes" when used in conjunction with the form builder names the parameters using a naming convention.... That was the real problem with what I was doing. I was not naming the variables correctly. Anyway thanks for your reply Zabba.
Great! I'm curious, what was the variable naming that worked? Could you show a short example in the comment? Thanks!
I did away with the nested parameters as I did not need it in the end. However if you examine a form that posts to a nested model you will see that the nested attributes are nameed: nested_attributes_for_<some_model>[<attribute_name>]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.