building a custom rails api for a rails/react/mongodb app.
GET requests working fine, but I can't get post to work.
Basically the params are not getting assigned to the object in my create method.
Request:
POST http://localhost:3000/api/v1/movies HTTP/1.1
{"title" : "Cool Movie"}
Here's my controller:
def create
movie = Movie.new(movie_params)
if movie.save
render json: MovieBlueprint.render(movie)
else
render json: { error: movie.errors.full_messages }, status: 422
end
end
private
def movie_params
params.except(:format).permit(:title, :description, :director, :genre)
end
output:
Parameters: {"{\"title\" : \"Cool Movie\"}"=>nil}
Unpermitted parameter: :{"title" : "Cool Movie"}
I get a 200 response with this. Basically the document is getting created in the database, but the fields / values are all still null. Why is it telling me unpermitted params?
And I know typically with rails you have to require the object like so:
params.require(:movie).permit(:title, :description, :director, :genre)
But when I try this, it makes matters worse, I get a 400 - bad request with this:
ActionController::ParameterMissing (param is missing or the value is empty: movie):
I assume this has something to do with the whole mongo thing and how I'm formatting my request, but I can't quite place it. Any help is appreciated.
CodePudding user response:
At a glance and considering the params coming into the controller via a POST
request needs to reference the entity it's changing, your data would need to should look like this to be available in the create
method:
{ "movie": { "title": "Updated Song Title" } }
Depending on the version of Rails being used, you could add a debugger
to test if the params are available. This will stop the runtime of the script and allow you to inspect it in the terminal.
Run your server in an individual process before trying this. For example, instead of running
bin/dev
runbin/rails server -p 3000
.
First, modify your create method to use debugger
:
def create
movie = Movie.new(movie_params)
debugger # <- Stop the script right here.
if movie.save
render json: MovieBlueprint.render(movie)
else
render json: { error: movie.errors.full_messages }, status: 422
end
end
Then, run the create
action of your controller by making a request to that endpoint with your params
of choice. Navigating to your terminal you'll see the program has stopped and you can type. Type params.inspect
to see if the movie
key is present:
params.inspect
Type continue
to let the rest of the program run.