Reputation: 55
I am currently learning rails and facing a totally weird issue. I am trying to update an existing article by following a tutorial that I am doing, however it is not getting updated. I am receiving the following errors from the terminal and browser respectively:
- Terminal:
* Started PATCH "/article/viewing-article-2" for 127.0.0.1 at 2018-03-28 18:54:46 +0200
* No route matches [PATCH] "/article/viewing-article-2"
- Browser: ActionController::RoutingError (No route matches [PATCH] "/article/viewing-article-2"):
My routes are such as
**routes.erb**
Rails.application.routes.draw do
root to: 'pages#index'
post 'article/create-new-article', to: 'pages#create'
get 'article/viewing-article-:id', to: 'pages#show', as: 'article'
get 'article/:id/edit', to: 'pages#edit', as: 'article_edit'
patch 'article/:id/update', to: 'pages#update', as: 'update_article'
get 'article/new-article', to: 'pages#new'
get 'article/destroy', to: 'pages#destroy'
end
and my controller:
controller.erb
def index
@articles = @@all_articles.all
end
def show
@article = Article.find(params[:id])
end
def edit
@article = Article.find(params[:id])
end
def update
@article = Article.find(params[:id])
article_params = params.require(:article).permit(:title, :author, :publisher, :content)
@article.update(article_params)
redirect_to root_path
end
and my html:
edit.html.erb
<% content_for :title do %>Editing <%= @article.title %><% end %>
<% content_for :bodycontent do %>
<h3>Editing <%= @article.title %></h3>
<%= form_for @article do |f| %>
<%= f.text_field :title, class: 'form-control'%>
<%= f.text_field :author, class: 'form-control'%>
<%= f.text_field :publisher, class: 'form-control'%>
<%= f.text_area :content, class: 'form-control'%>
<%= f.submit class: 'form-control btn btn-primary' %>
<% end %>
<% end %>
I am not surely what I am doing wrong, as the selected article does not get updated.
I have loved rails so far, and hope to get better at it. Will appreciate any help.
Upvotes: 1
Views: 460
Reputation: 2004
Modify form_for
as follows with custom url
<%= form_for @article, url: @article.new_record? ? article_create_new_article_path : update_article(@post)do |f| %>
but I will suggest you to use Resourceful Routing instead.
Upvotes: 1
Reputation: 765
At first, you really should using resource routing for you article model:
Rails.application.routes.draw do
root 'pages#index'
resources :articles
end
This is what controller should look like. About permit params read here.
def index
@articles = Article.all
end
def show
@article = Article.find(params[:id])
end
def edit
@article = Article.find(params[:id])
end
def update
return unless request.patch?
@article = Article.find(params[:id])
if @article.update(article_params)
redirect_to root_path
else
render :edit
end
end
private
def article_params
params.require(:article).permit(:title, :author, :publisher, :content)
end
Upvotes: 1