friendly_id在UPDATE上创建新条目

时间:2015-07-13 10:42:38

标签: ruby-on-rails ruby friendly-id

我正在使用friendly_id 5.1.0,当我尝试更新条目时,例如创建新文章,而不是更新条目的数据,它会创建一个新条目。 我已经标题了,当我在编辑文章时没有改变它时,它会创建一个带有一堆数字/字母的slu ::

http://localhost:3000/articles/first-article-2d392b8e-92b8-44b0-ad67-50dd674f7aaa

这是我的文章.rb模型:

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

当我添加:use => [:slugged, :history]时,当我更新条目并保持相同的标题时,由于我的:slug字段为unique :true,因此无法保存该条目。 这是我的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

这是我的(未完成)项目的GitHub存储库:https://github.com/TheDoctor314/blog

3 个答案:

答案 0 :(得分:1)

此问题与FriendlyID无关。

您的问题是 here newedit上使用的表单):

<%= bootstrap_form_for :article, url: articles_path do |f| %>

它不会尝试使用您的@article对象来构建该表单。因此,您的表单始终会向POST发出articles_path个请求,每次都会产生create。你应该做的是:

<%= bootstrap_form_for @article do |f| %>

这样,表单构建器将检查该对象是否已persisted?,如果是,则生成一个表单,该表单向触发PATCH操作的特定文章发出update请求。它会尝试自己猜测URL。只有当你严格遵守惯例时,它才会成功。

如果@article不是persisted?,则会执行以下操作:将POST设为articles_path

答案 1 :(得分:0)

在params中允许id

params.require(:article).permit(:id, :title, :text)

希望有所帮助!

答案 2 :(得分:0)

“编辑”表单正在路由以创建文章控制器的操作,而不是更新操作。编辑文件时,您需要更改表单路径。

如果您看到文章索引操作,则可以看到正在添加新文章,而不是更新

相关问题