2016-08-31 233 views
0

我找不到屬性:description返回nil的錯誤。 從rails console爲什麼屬性:描述返回零

@book = Book.first 
# Book Load (0.7ms) SELECT "books".* FROM "books" ORDER BY "books"."id" ASC LIMIT 1 
#=> #<Book id: 1, title: "A Game of Thrones", description: nil, author: "George R. R. Martin ", created_at: "2016-09-01 13:27:09", updated_at: "2016-09-01 13:27:09"> 

books_controller.rb

class BooksController < ApplicationController 

    before_action :find_book, only: [:show, :edit, :update, :destroy] 

    def index 
    @books = Book.all.order("created_at DESC") 
    end 

    def show 
    @book = Book.find(params[:id]) 
    end 

    def new 
    @book = Book.new 
    end 

    def create 
    @book = Book.new(book_params) 

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

    private 

    def book_params 
    params.require(:book).permit(:description, :title, :author) 
    end 

    def find_book 
    @book = Book.find(params[:id]) 
    end 

end 

_form.html.erb

<%= f.input :title, label: "Book Title" %> 
<%= f.input :description %> 
<%= f.input :author %> 
<%= f.button :submit %> 

'show.html.erb'

<h2><%= @book.title %></h2> 
<h3><%= @book.author %></h3> 
<h2><%= @book.description %></h2> 

routs.rb

'Rails.application.routes.draw做 資源:書籍 根 '的書#指數' 結束'

+0

我想你已經試圖通過你的'BooksController'從表單創建一本書。你可以顯示已經傳遞給你的控制器的參數嗎?您可以在應用程序的日誌文件中找到它們。 – Stefan

+2

嘗試創建新記錄,甚至可以看到沒有描述。 from Console –

+0

您正在使用哪個版本的Rails?你有沒有在Gemfile中聲明的「protected_attributes」gem?你的'Book'模型中有「attr_accessible」嗎? – romainsalles

回答

0

檢查PARAMS哈希通過創建行動創造的書。我認爲描述會丟失。

你可以在這裏粘貼params散列嗎?

+0

這是一條評論而不是答案。 – engineersmnky

+0

我可以在哪裏檢查params哈希?你的意思是這樣的: 「DEF book_params \t params.require(:書).permit(:描述:標題:作者) 結束」 –

+0

沒有,如果你正在運行在開發模式在本地的應用程序,然後檢查您的Rails服務器正在運行的日誌。當你提交表格時,日誌會在那裏生成。在那裏你可以看到傳遞給該動作的params散列。 – prashant