小编Kyl*_*ing的帖子

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

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

ruby api routes ruby-on-rails

5
推荐指数
1
解决办法
102
查看次数

标签 统计

api ×1

routes ×1

ruby ×1

ruby-on-rails ×1