首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NoMethodError in Books#create

NoMethodError in Books#create
EN

Stack Overflow用户
提问于 2017-05-07 21:54:34
回答 1查看 153关注 0票数 1

我正在学习Rails,我被这个问题困住了。我看过其他类似的问题,但没有找到对我有用的解决方案。

一切正常工作,但随后我添加了一个f.file_field,允许用户选择图像。现在,如果用户选择一个图像,我会得到这个错误,但是如果他没有,我就不会得到错误。

这是我的书模型

代码语言:javascript
复制
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

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

代码语言:javascript
复制
  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

这就是我们的观点

代码语言:javascript
复制
<%= 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 :Ruby2.2.6p396

Rails : Rails 5.0.2

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-05-07 22:19:07

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

代码语言:javascript
复制
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变量中填充可用类别的选择标记。该变量仅在new操作中设置。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43837120

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档