I'm using friendly_id 5.1.0, and when I try to update an entry, for exemple creating a new Article, instead of updating the data of the entry, it creates a new one. I have slugged the title and when I don't change it when editing an article, it creates a slug with a bunch of numbers/letters :
http://localhost:3000/articles/first-article-2d392b8e-92b8-44b0-ad67-50dd674f7aaa
Here's my article.rb Model :
class Article < ActiveRecord::Base
extend FriendlyId
has_many :comments
friendly_id :title, :use => :slugged
validates :title, presence: true,
length: { minimum: 5}
def should_generate_new_friendly_id?
new_record? || title_changed?
end
when I add :use => [:slugged, :history]
, when I update an entry and keep the same title, it can't save it because my :slug
field is unique :true
.
Here's my articles_controller.rb :
class ArticlesController < ApplicationController
def index
@articles = Article.all.order(created_at: :desc)
end
def show
@article = Article.friendly.find(params[:id])
if request.path != article_path(@article)
redirect_to @article, status: :moved_permanently
end
end
def new
@article = Article.new
end
def edit
@article = Article.friendly.find(params[:id])
end
def create
@article = Article.new(article_params)
if @article.save
redirect_to @article
else
render 'new'
end
end
def update
@article = Article.friendly.find(params[:id])
if @article.update(article_params)
redirect_to @article
else
render 'edit'
end
end
def destroy
@article = Article.friendly.find(params[:id])
@article.destroy
redirect_to articles_path
end
private
def article_params
params.require(:article).permit(:title, :text)
end
end
Here's my GitHub repository whith my (unfinished) project : https://github.com/TheDoctor314/blog
This issue has nothing to do with FriendlyID.
Your problem is here (a form used on both new
and edit
):
<%= bootstrap_form_for :article, url: articles_path do |f| %>
It does not attempt to use your @article
object to built that form. So your form always issues a POST
request to articles_path
, which results in create
every time. What you should do instead is:
<%= bootstrap_form_for @article do |f| %>
That way form builder will check if that object is persisted?
already, and if so, generate a form that issues a PATCH
request to that specific article that triggers an update
action. It will try to guess the URL by itself. And it will succeeed only if you follow conventions tightly enough.
If @article
is not persisted?
, it will do what it did: make a POST
to articles_path
.