繁体   English   中英

Rails-回形针-NoMethodError

[英]Rails- paperclip- NoMethodError

我正在尝试制作电影评论应用程序。 这包括添加电影图像和文本字段。 我正在使用回形针gem进行图像上传。 添加电影时出现此错误。

Movies#create中的NoMethodError

Showing - MovieReview/app/views/movies/_form.html.erb where line #2 raised:

undefined method `map' for nil:NilClass
Trace of template inclusion: app/views/movies/new.html.erb

Rails.root: /Review/MovieReview

我正在我的movie / new,html.erb中渲染部分表单。 以下是来自movie / _form.html.erb的代码段

<%= simple_form_for @movie, :html => { :multipart => true} do |f| %>
   <%= select_tag(:category_id, options_for_select(@categories), :prompt => "Select a Category") %>

  <%= f.file_field :movie_img %>
  <%= f.input :title, label: "Movie Title" %>
  <%= f.input :description %>
  <%= f.input :director %>
  <%= f.button :submit %>

电影控制器

class MoviesController < ApplicationController
  def new
        @movie = current_user.movies.build
        @categories = Category.all.map{ |c| [c.name, c.id] }
    end

    def create
        @movie = current_user.movies.build(movie_params)
        @movie.category_id = params[:category_id]

        if @movie.save
            redirect_to root_path
        else
            render 'new'
        end
    end

PS:我在movie_params方法中添加了图片参数,该参数位于私有部分中-以下是代码段

def movie_params
        params.require(:movie).permit(:title, :description, :director, :category_id, :movie_img)
    end

电影模型

class Movie < ActiveRecord::Base
    belongs_to :user
    belongs_to :category

  has_attached_file :movie_img, styles: { movie_index: "250x350>", movie_show: "325x475>" }, default_url: "/images/:style/missing.png"
  validates_attachment_content_type :movie_img, content_type: /\Aimage\/.*\Z/
end

分类模型

class Category < ActiveRecord::Base
    has_many :movies
end

您没有在Movies#create操作中定义@categories实例变量。

添加此代码:

@categories = Category.all.map{ |c| [c.name, c.id] }

进入create方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM