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
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 %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With