2017-01-02 63 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

如果可能的话,请在这里分享错误 –

相关问题