Using postman to POST a bit of JSON to be created in a DB, there is a code snippet for you to test with. Getting an error that says the method 'movie' is undefined, but that method is never called.
{"movie": {
"title": "Its a Mad Mad Word",
"year": "1967",
"summary": "So many big stars"
}
}
Below is the code, and the error is as follows:
undefined method 'movie' for #<Movie:0x007fcfbd99acc0>
class ApplicationController < ActionController::Base
protect_from_forgery with: :null_session
end
module API
class MoviesController < ApplicationController
...
def create
movie = Movie.new({
title: movie_params[:title].to_s,
year: movie_params[:year].to_i,
summary: movie_params[:summary].to_s
})
if movie.save
render json: mov, status: 201
else
render json: mov.errors, status: 422
end
end
private
def movie_params
params.require(:movie).permit(:title, :year, :summary)
end
end
end
class Movie < ActiveRecord::Base
validates :movie, presence: true
end
class CreateMovies < ActiveRecord::Migration
def change
create_table :movies do |t|
t.string :title
t.integer :year
t.text :summary
t.timestamps null: false
end
end
end
Rails.application.routes.draw do
namespace :api do
resources :movies, only: [:index, :show, :create]
end
end
Validations are used to ensure that only valid data is saved into your database, so you should validate movie's fields(title, year, summary)
validates :movie, presence: true
change it to:
validates :title, presence: true
validates :year, presence: true
validates :summary, presence: true
You can get more info from here
/edit by huanson you can also sum it up:
validates :title, :year, :summary, presence: true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With