Question

I'm working on a Rails 4 API where the client can post data to the controller and it will save in a database. I was wondering how i could implement the user to POST nested JSON and then have the controller accept the attributes and create a model with them. The JSON would look something like

{
  'identifier': {
    'name': 'Test'
  }
}

Then in a private method i have

def parameters
    params.respond_to?(:permit) ?
        params.require(:picture).permit(:identifier) :
        params[:picture].slice(:identifier) rescue nil
  end

And when i try to access the 'name' parameter in my controller as parameters[:identifier][:name] i get undefined method []. Any suggestions?

Create Action

@picture = current_user.pictures.new(name: parameters[:identifier][:name])

Picture model only has t.string :name

Was it helpful?

Solution 2

You can use nested JSON as long as you create them in your permitted parameters such as:

  def parameters
    params.respond_to?(:permit) ?
        params.require(:picture).permit(:identifier => [ :name ]) :
        params[:picture].slice(:identifier => [ :name ]) rescue nil
  end

This works on Rails 4 using Strong Parameters

OTHER TIPS

Looks like the JSON has the string 'identifier' as a key whereas you are trying to access it with a symbol :identifier, which returns nil. So [] is not defined on nil. You should probably do parameters["identifier"]["name"].

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