2017-05-07 28 views
1

我在學習Ruby on Rails,並且遇到了這個問題。我查看了其他類似的問題,但沒有找到適合我的解決方案。書中的NoMethodError#create

一切正常,但我添加了一個f.file_field允許用戶選擇圖像。現在,如果用戶選擇一個圖像,我得到這個錯誤,但如果他不,我不會得到這個錯誤。

enter image description here

這是我的書

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

+0

重新啓動服務器,然後重試。另外,你的「類別」表中有記錄嗎? – amrrbakry

+0

我重新啓動了服務器多次。我手動添加了類別,每本書都有一個category_id – CNuts

+0

'strong params'中的'book_img'? –

回答

1

您需要設置裏面create行動@categories變量。如果create行動失敗,它呈現new模板,試圖填充select標籤可用類別內@categories變量更新如下

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 

。此變量僅在new操作中設置。

+0

謝謝你的回答。這確實解決了錯誤,但是你是否知道爲什麼它不創建新書? – CNuts

+0

最有可能是因爲'book_img'上的驗證。嘗試在保存失敗後檢查'@ book.errors'。它應該告訴問題是什麼。 –

+0

雅我收到了回形針寶石錯誤,我可能沒有正確安裝它。感謝您的幫助。 – CNuts

相關問題