2017-07-25 15 views
0

我想在rails 5上構建一個簡單的博客。我創建了一個樁模型:軌道上的紅寶石不能使用permit.require

create_table "posts", force: :cascade do |t| 
    t.string "title" 
    t.text "body" 
    t.integer "category_id" 
    t.integer "author_id" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
end 

我的控制器方法:

def new 
    @post = Post.new 
    @categories = Category.all 

end 

def create 
    @post = Post.new(post_params) 
    if @post_save 
     redirect_to posts_path, :notice => "Post has benn created" 
    else 
     render "new" 
    end 

end 

def post_params 
    params.require(:post).permit(:title, :body, :category_id) 
end 

當我嘗試通過HTML表單沒有任何反應添加另一篇文章。帶有表格的頁面被重新加載,並且帖子本身不被保存。我究竟做錯了什麼?

回答

2

這是因爲有一個在create方法錯字

@post_save必須@post.save

def create 
    @post = Post.new(post_params) 
    if @post.save 
    redirect_to posts_path, :notice => "Post has been created" 
    else 
    render "new" 
    end 
end 

由於@post_save沒有定義,else塊進行評估,new呈現頁並沒有任何反應

+0

是的。那是我的錯誤。現在一切正常。謝謝伊戈爾! – Jacek717

0

我認爲你也應該允許:author_id,如果你的表單中有這樣一個字段。因爲,據我所知,發佈belongs_to:作者。這意味着author_id在創建後是必需的。 而且,你有一個錯字,你應該改變「@post_save」=>「@ post.save!」 (在前面的答案中提到過)。