2014-07-17 51 views
10

我收到以下錯誤:的ActionController :: UrlGenerationError在文章#編輯

沒有路由匹配{:動作=> 「秀」,:控制器=> 「文章」,:ID =>零}缺少必需的鍵:[: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 
+0

你可以發佈你的'rake routes'輸出嗎? – Pavan

+0

我已經在問題本身中包含了rake路由輸出 – user3726986

+0

當您將該行更改爲'<%= form_for @article,url:article_path(@article),method :: patch do | f |時,會發生什麼? %>'? – Pavan

回答

5

如果你看一下你的問題

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

檢查網址:article_path(@article)這是你的文章顯示的行動路徑和助手如果您檢查您的耙路線它說爲顯示操作,您需要一個get請求,但您使用的是一個patch方法,或者如果您正在嘗試編輯一篇文章,那麼您的路徑助手是錯誤的,因此沒有路由錯誤

修復

要顯示的文章:

如果你想顯示的文章則代替的form_for使用的link_to它默認使用GET請求的,的form_for是用於製作文章而不用於展示文章

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

創建或編輯文章:

a。 使用多態的URL

如果你想創建一個文章或編輯的文章,那麼你可以使用軌多態性網址,並不需要指定網址選項,軌道將在內部處理這個問題。因此,用於創建和編輯了一篇文章,你可以用同樣的形式

<%= 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 %> 
+0

我有這個確切的問題,並嘗試編輯一篇文章多態urls和path_helpers沒有幫助。 path_helpers出現同樣的錯誤,ArgumentError出現多態url。此材料來自[本教程教程](http://guides.rubyonrails.org/getting_started.html#updating-articles)。我不確定堆棧溢出最佳實踐是爲了恢復一個老問題,但我想在發表一篇新文章之前留言。 –

+1

原來我是個白癡,沒有注意到'''def編輯...''''''''''''''''''''''''''這是我錯過的代碼。忽略上面的評論。 –

+0

@ user1489726沒有問題。很高興聽到你的工作:) – Mandeep

相關問題