RoR - #电影的未定义方法"电影":0x007fa43a0629e0>

Kyl*_*ing 5 ruby api routes ruby-on-rails

使用postman来POST一些要在DB中创建的JSON,有一个代码片段供你测试.获取一个错误,指出方法'movie'未定义,但该方法永远不会被调用.

{"movie": {
     "title": "Its a Mad Mad Word",
     "year": "1967",
     "summary": "So many big stars"
     }
 }
Run Code Online (Sandbox Code Playgroud)

下面是代码,错误如下:

undefined method 'movie' for #<Movie:0x007fcfbd99acc0>

应用控制器

class ApplicationController < ActionController::Base
  protect_from_forgery with: :null_session
end
Run Code Online (Sandbox Code Playgroud)

调节器

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
Run Code Online (Sandbox Code Playgroud)

模型

class Movie < ActiveRecord::Base
    validates :movie, presence: true
end
Run Code Online (Sandbox Code Playgroud)

移民

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
Run Code Online (Sandbox Code Playgroud)

路线

Rails.application.routes.draw do
  namespace :api do
    resources :movies, only: [:index, :show, :create]
  end
end
Run Code Online (Sandbox Code Playgroud)

pan*_*ang 4

验证用于确保仅将有效数据保存到数据库中,因此您应该验证电影的字段(标题、年份、摘要)

 validates :movie, presence: true
Run Code Online (Sandbox Code Playgroud)

将其更改为:

validates :title, presence: true
validates :year, presence: true
validates :summary, presence: true
Run Code Online (Sandbox Code Playgroud)

您可以从这里获取更多信息

/huanson编辑 你也可以总结一下:

validates :title, :year, :summary, presence: true
Run Code Online (Sandbox Code Playgroud)