2016-05-26 62 views
0

我正在嘗試在rails中製作電影評論應用程序。這包括添加電影圖像和文本字段。我正在使用回形針創建圖片上傳。我在添加電影時遇到此錯誤。在電影#Rails-回形針 - NoMethodError

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 

我渲染的形式在部分我的電影/新,html.erb。以下是從 電影的代碼片段/ _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 
+0

我認爲你的'@categories = Category.all.map {| c | [c.name,c.id]}'line –

+0

'Category'表中是否有'record' –

+0

是的,我的類別表中有記錄。我將編輯問題並在我的問題中添加類別模型片段 –

回答

0

您還沒有定義在Movies#create行動@categories實例變量。

添加以下代碼:

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

create方法。

+0

在create方法中添加了代碼。現在不顯示錯誤。但仍不能添加新電影。當我點擊創建按鈕時,我被重定向到創建頁面。 –