gpt4 book ai didi

ruby-on-rails - RoR - # 的未定义方法 `movie'

转载 作者:数据小太阳 更新时间:2023-10-29 07:16:48 25 4
gpt4 key购买 nike

使用 postman POST 一些要在数据库中创建的 JSON,有一个代码片段供您测试。收到一条错误消息,指出方法“电影”未定义,但从未调用过该方法。

{"movie": {
"title": "Its a Mad Mad Word",
"year": "1967",
"summary": "So many big stars"
}
}

下面是代码,错误如下:

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

应用程序 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

型号

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

最佳答案

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

 validates :movie, presence: true

将其更改为:

validates :title, presence: true
validates :year, presence: true
validates :summary, presence: true

您可以从 here 获得更多信息

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

validates :title, :year, :summary, presence: true

关于ruby-on-rails - RoR - #<Movie :0x007fa43a0629e0> 的未定义方法 `movie',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32707267/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com