使用邮递员POST一些要在数据库中创建的JSON,有一个代码片段供您测试。获取一个错误,指出方法'movie'未定义,但该方法永远不会被调用。
{"movie": {
"title": "Its a Mad Mad Word",
"year": "1967",
"summary": "So many big stars"
}
}
下面是代码,错误如下:
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
答案 0 :(得分:4)
验证用于确保只有有效数据保存到您的数据库中,因此您应该验证电影的字段(标题,年份,摘要)
validates :movie, presence: true
将其更改为:
validates :title, presence: true
validates :year, presence: true
validates :summary, presence: true
您可以从here
获取更多信息/由huanson编辑 你也可以总结一下:
validates :title, :year, :summary, presence: true