Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually creating parameter hash rails

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.

like image 411
Paul Barclay Avatar asked Nov 04 '11 12:11

Paul Barclay


1 Answers

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)
like image 90
gmaliar Avatar answered Sep 26 '22 01:09

gmaliar