2017-01-02 61 views
0

我正在使用官方指南中的Ruby on Rails應用程序。我創建的模型後,我做的form_for在app /視圖/ new.html.erb這樣博客中的ActionController :: UrlGenerationError#new

<%= form_for :blog, url: blog_path do |f| %> 
    <p> 
    <%= f.label :title %> 
    <%= f.text_field :title %> 
    #some other stuff 
    <%= f.submit %> 
<% end %> 

但是我reciving錯誤

ActionController::UrlGenerationError in Blog#new 

Showing <some folders>/hello_world/app/views/blog/new.html.erb where line #1 raised: 
No route matches {:action=>"show", :controller=>"blog"} missing required keys: [:id] 
Extracted source (around line #1): 
<%= form_for :blog, url: blog_path do |f| %> 

我不知道爲什麼會出現這種情況,bacause的我路線看起來是正確的。我的路線文件:

Rails.application.routes.draw do 
    resources :users 
    resources :blog 
end 

這是我blog_controller:

class BlogController < ApplicationController 
    def index 
    @posts = Post.all 
    end 

    def new 
    end 

    private 
    def post_params 
     params.require(:blog).permit(:title, :text) 
    end 
end 

我加入

def create 
    @post = Post.new(post_params) 
    if @post.save 
     redirect_to @post 
    else 
     render 'new' 
    end 
    end 

,但它並沒有幫助

該錯誤不顯示當我刪除來自form_for(「url:blog_path」)的url屬性,但顯然它不工作,因爲或形成目標。我在項目中有一些其他文件,但我認爲它們對於這個問題並不重要。

回答

0

修改你的新方法的代碼在控制器如下

def new 
    @blog = Blog.new 
end 

,然後改變你的形式如下

<%= form_for @blog, url: {action: "create"} do |f| %> 
    <p> 
    <%= f.label :title %> 
    <%= f.text_field :title %> 
    #some other stuff 
    <%= f.submit %> 
<% end %> 

或者乾脆你可以創建窗體本身

<%= form_for Blog.new do, url: {action: "create"} |f| %> 
    <p> 
    <%= f.label :title %> 
    <%= f.text_field :title %> 
    #some other stuff 
    <%= f.submit %> 
<% end %> 
對象

希望這會幫助你。

+0

它有助於局部。我不再有錯誤,但我的post_params私人方法會導致錯誤。我從工作的博客應用程序中複製代碼,但仍然在收回錯誤,所以我刪除了項目並創建了新的。 – AbUndZu

+0

如果可能的話,請在這裏分享錯誤 –

相關問題