Books#create中的NoMethodError

时间:2017-05-07 21:54:34

标签: ruby-on-rails ruby

我正在学习Ruby on Rails,我遇到了这个问题。我看过其他类似的问题,但没有找到适合我的解决方案。

一切正常但后来我添加了f.file_field以允许用户选择图像。现在,如果用户选择图像,我会收到此错误,但如果他没有,我就不会收到错误。

enter image description here

这是我的Book

模型
class Book < ApplicationRecord
  belongs_to :user
  belongs_to :category

  has_attached_file :book_img, styles: { book_index: "250x350>", book_show: "325x475>" }, default_url: "/images/:style/missing.png"
  validates_attachment_content_type :book_img, content_type: /\Aimage\/.*\z/

end

这是我认为导致错误的控制器的一部分

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

  def create
    @book = current_user.books.build(book_params)
    @book.category_id = params[:category_id]

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

这是视图

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

<% end %>

我不明白为什么我在select_tag上收到错误,允许用户选择图书的类别。

Ruby:ruby 2.2.6p396

Rails:Rails 5.0.2

1 个答案:

答案 0 :(得分:1)

您需要在@categories操作中设置create变量。更新如下

def create
  @book = current_user.books.build(book_params)
  @book.category_id = params[:category_id]

  if @book.save
    redirect_to root_path
  else
    @categories = Category.all.map{ |c| [c.name, c.id] }
    render 'new'
  end
end

如果create操作失败,则会呈现new模板,该模板会尝试使用@categories变量中的可用类别填充select标记。此变量仅在new操作中设置。