我在學習Ruby on Rails,並且遇到了這個問題。我查看了其他類似的問題,但沒有找到適合我的解決方案。書中的NoMethodError#create
一切正常,但我添加了一個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
上遇到錯誤,它允許用戶選擇書的類別。
紅寶石:紅寶石2.2.6p396
的Rails:Rails的5.0.2
重新啓動服務器,然後重試。另外,你的「類別」表中有記錄嗎? – amrrbakry
我重新啓動了服務器多次。我手動添加了類別,每本書都有一個category_id – CNuts
'strong params'中的'book_img'? –