Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActionController::UrlGenerationError in Articles#edit

I am getting the following error:

No route matches {:action=>"show", :controller=>"articles", :id=>nil} missing required keys: [:id]

Following is the code where error is shown.

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

What is this error,whenever I click edit from previous screen , I think I am sending the article id.

Here is my rake routes output

     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
like image 960
user3726986 Avatar asked Jul 17 '14 06:07

user3726986


1 Answers

If you look at your question

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

Check your url: article_path(@article) this is the path helper for your article show action and if you check your rake routes it says for show action you need a get request but you are using a patch method or if you are trying to edit an article then your path helper is wrong and hence no route error

Fix

To show an article:

If you want to show an article then instead of a form_for use link_to which by default use a get request, form_for is used to create an article and not for showing an article

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

To create or edit an article:

a. Using polymorphic urls

If you want to create an article or edit an article then you can use rails polymorphic urls and don't need to specify url option, rails will handle this internally. So for creating and editing an article you can use the same form

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

For this to work you need to have this in your controller

def new
  @article = Article.new
end

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

b. Using path_helpers

If you'll hardcode url option in your form then it'll take you to that action only and hence you'll require separate forms

For creating:

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

For editing:

<%= form_for :article, url: article_path(@article) do |f| %>
  // your fields
<% end %>
like image 185
Mandeep Avatar answered Oct 30 '22 16:10

Mandeep