文章#edit中的ActionController :: UrlGenerationError

时间:2014-07-17 06:14:05

标签: ruby-on-rails ruby

我收到以下错误:

没有路由匹配{:action =>" show",:controller =>"文章",:id => nil}缺少必需的密钥:[:id]

以下是显示错误的代码。

<%= form_for :article, url: article_path(@article), method: :patch do |f| %>

这是什么错误,每当我点击上一屏幕的编辑时,我想我正在发送文章ID。

这是我的佣金路线输出

     Prefix Verb   URI Pattern                  Controller#Action
welcome_index GET    /welcome/index(.:format)     welcome#index
     articles GET    /articles(.:format)          articles#index
              POST   /articles(.:format)          articles#create
  new_article GET    /articles/new(.:format)      articles#new
 edit_article GET    /articles/:id/edit(.:format) articles#edit
      article GET    /articles/:id(.:format)      articles#show
              PATCH  /articles/:id(.:format)      articles#update
              PUT    /articles/:id(.:format)      articles#update
              DELETE /articles/:id(.:format)      articles#destroy
         root GET    /                            welcome#index

1 个答案:

答案 0 :(得分:5)

如果你看看你的问题

<%= form_for :article, url: article_path(@article), method: :patch do |f| %>

检查您的网址:article_path(@article)这是您的文章展示操作的路径助手,如果您检查您的展示路线,那么您需要get请求但是您正在使用{patch请求1}}方法或者如果您正在尝试编辑文章,那么您的路径助手是错误的,因此没有路由错误

<强>修正

要展示文章:

如果你想显示一篇文章,而不是一个form_for使用link_to,默认情况下使用get请求 form_for用于创建文章而不是用于显示文章

<%= link_to "Article", articles_path(@article) %>

创建或编辑文章:

一个。 使用多态网址

如果您想创建文章或编辑文章,那么您可以使用 rails polymorphic urls 并且不需要指定url选项,rails将在内部处理此问题。因此,对于创建和编辑文章,您可以使用相同的表单

<%= form_for @article do |f| %>
  // your fields
<% end %>

为此,您需要在控制器中使用

def new
  @article = Article.new
end

def edit
  @article = Article.find(params[:id])
end

使用path_helpers

如果您在表单中硬编码网址选项,那么它只会带您进行该操作,因此您需要单独的表单

用于创建:

<%= form_for :article, url: article_path do |f| %>
  // your fields
<% end %>

进行编辑:

<%= form_for :article, url: article_path(@article) do |f| %>
  // your fields
<% end %>