我正在学习Rails,我被这个问题困住了。我看过其他类似的问题,但没有找到对我有用的解决方案。
一切正常工作,但随后我添加了一个f.file_field,允许用户选择图像。现在,如果用户选择一个图像,我会得到这个错误,但是如果他没有,我就不会得到错误。

这是我的书模型
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 :Ruby2.2.6p396
Rails : Rails 5.0.2
发布于 2017-05-07 22:19:07
您需要在@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变量中填充可用类别的选择标记。该变量仅在new操作中设置。
https://stackoverflow.com/questions/43837120
复制相似问题