Ruby on rails:未定义的方法`map'对于nil:NilClass,是什么原因造成的?当我向表添加记录

时间:2016-08-22 09:56:40

标签: ruby-on-rails ruby

这是我的_form.html.erb

<%= simple_form_for @book,:html => { :multipart => true }  do |f| %>
<%= select_tag(:category_id, options_for_select(@categories), :promt => "Select a category") %>
<%= f.file_field :book_img %>
<%= f.input :title, label: "Book Title" %>
<%= f.input :description %>
<%= f.input :author %>
<%= f.button :submit %>

这是我的BooksController

class BooksController < ApplicationController

before_filter :initialize_book
before_action :find_book, only: [:show, :edit, :update, :destroy]

def initialize_book
    @book = Book.new
end


def show
    @book =Book.find(params[:id])
end

def index
    if params[:category].blank?
        @books = @books = Book.all.order("created_at DESC")
    else
        @category_id = Category.find_by(name: params[:category]).id
        @books = Book.where(:category_id => @category_id).order("created_at DESC")
    end     
end

def new
    @book = current_user.books.build  # Book.new 
    @categories = Category.all.map{ |c| [c.name, c.id]} 
end

def create
    @book =current_user.books.build(book_params)  # Book.new(book_params) 
    @book.category_id = params[:category_id]
    if @book.save
        redirect_to root_path
    else
        render 'new'
    end
end

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

def update
    @book.category_id = params[:category_id]
    if @book.update(book_params)
        redirect_to book_path(@book)
    else
        render 'edit'
    end
end

def destroy
    @book.destroy
    redirect_to root_path
end

private
    def book_params
        params.require(:book).permit(:title, :description, :author, :category_id, :book_img)
    end

    def find_book
        @book =Book.find(params[:id])
    end

book.rb

&#13;
&#13;
class Book < ActiveRecord::Base
	belongs_to :user
	belongs_to :category
	has_attached_file :book_img, styles: { book_index: "250x250>", book_show: "325x475>" }, default_url: "/images/:style/missing.png"
  	validates_attachment_content_type :book_img, content_type: /\Aimage\/.*\z/
end
&#13;
&#13;
&#13;

我安装了paperclip gem以将图像添加到Book,这是我运行Rails迁移生成器时创建的文件:rails generate paperclip Book book_img

&#13;
&#13;
class AddAttachmentBookImgToBooks < ActiveRecord::Migration
  def self.up
    change_table :books do |t|
      t.attachment :book_img
    end
  end

  def self.down
    remove_attachment :books, :book_img
  end
end
&#13;
&#13;
&#13;

但是当我添加Book并将图像添加到Book时显示错误

&#13;
&#13;
NoMethodError in Books#create
Showing C:/Sites/BookReview/app/views/books/_form.html.erb where line #2 raised:

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

Rails.root: C:/Sites/BookReview

Application Trace | Framework Trace | Full Trace
app/views/books/_form.html.erb:2:in `block in _app_views_books__form_html_erb___232429848_42489936'
app/views/books/_form.html.erb:1:in `_app_views_books__form_html_erb___232429848_42489936'
app/views/books/new.html.erb:3:in `_app_views_books_new_html_erb__358042162_78928608'
app/controllers/books_controller.rb:39:in `create'
Request

Parameters:

{"utf8"=>"✓",
 "authenticity_token"=>"kuaFBEmKqeVwLRr+NWke5AS5GxqPK0O/rOSPwDrc+8GsERzW0AlTJvhUji8/OevAIYhETyKc+jiNC3XIvpTAxQ==",
 "category_id"=>"3",
 "book"=>{"book_img"=>#<ActionDispatch::Http::UploadedFile:0x91a4060 @tempfile=#<Tempfile:C:/Users/muitr/AppData/Local/Temp/RackMultipart20160822-11652-1id5vn1.jpg>,
 @original_filename="csharp.jpg",
 @content_type="image/jpeg",
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

您只为编辑操作设置类别,但是新的内容是什么? 试试这个:

before_action :set_categories, only: [:new,:create, :edit]
private
def set_categories
@categories = Category.all.map{ |c| [c.name, c.id]} 
end

答案 1 :(得分:1)

此行app/controllers/books_controller.rb:39:in create'表示方法create中出现错误。在create内,您不能设置@categories。 您之前的过滤器和操作仅设置@book

render :new未执行您的new方法。它仅呈现new的给定模板。因此@categories仍为nil