0

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

1
  • 1
    Post the code for create action of your controller & also what fields you have in database i.e your models Commented Jul 28, 2013 at 18:35

2 Answers 2

1

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"].

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

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.