Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RoR - undefined method `movie' for #<Movie:0x007fa43a0629e0>

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>

Application Controller

class ApplicationController < ActionController::Base
  protect_from_forgery with: :null_session
end

Controller

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

Model

class Movie < ActiveRecord::Base
    validates :movie, presence: true
end

Migration

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

Routes

Rails.application.routes.draw do
  namespace :api do
    resources :movies, only: [:index, :show, :create]
  end
end
like image 707
Kyle King Avatar asked Sep 27 '22 16:09

Kyle King


1 Answers

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
like image 70
pangpang Avatar answered Sep 30 '22 03:09

pangpang