首页 > 解决方案 > 简单的表单和表单对象 - 一种用于新建和编辑的表单

问题描述

我试图找到以下问题的答案,但我失败了。

我正在使用表单对象创建 simple_form,但我不知道应该在 simple_form 中指定哪个 URL,以便为新操作和更新操作重用相同的表单。

这是我的代码:ArticlesController:

class ArticlesController < ApplicationController

...

  def new
    @article = Article.new
    @article_form = ArticleForm.new(@article)
  end

  def create
    @article = Article.new
    @article_form = ArticleForm.new(@article)
    if @article_form.save(article_params)
      flash[:notice] = 'You have added a new article.'
      redirect_to @article_form.article
    else
      flash[:danger] = 'Failed to add new article.'
      render :new
    end
  end

  def edit
    @article = Article.find(params[:id])
    @article_form = ArticleForm.new(@article)
    # binding.pry
  end

  def update
    @article = Article.find(params[:id])
    @article_form = ArticleForm.new(@article)
    if @article_form.save(article_params)
      flash[:success] = 'Article updated'
      TagServices::OrphanTagDestroyer.call
      redirect_to @article_form.article
    else
      flash[:error] = 'Failed to update the article'
      render :edit
    end
  end
end

要在新/编辑操作中呈现的表单:

= simple_form_for @article_form, url: article_path do |f|
  = f.input :title, label: "Article title:"
  = f.input :body, label: "Body of the article:", as: :text, input_html: { :style => 'height: 200px' }
  = f.input :tags_string, label: "Tags:", input_html: { value: f.object.all_tags }
  = f.button :submit, 'Send!'

文章形式:

class ArticleForm
  include ActiveModel::Model
  delegate :title, :body, :author_id, :tags, :id, :persisted?, to: :article
  attr_accessor :article
  validates_presence_of :title, :body, :tags
  validate :validate_prohibited_words

  def initialize(article)
    @article = article
  end

  def save(article_params)
    @article.update_attributes(article_params.slice('title', 'body', 'author_id'))
    @article.tags = tag_list(article_params[:tags_string])

    if valid?
      @article.save!
      true
    else
      false
    end
  end

  def tag_list(tags_string)
    tags_string.scan(/\w+/)
               .map(&:downcase)
               .uniq
               .map { |name| Tag.find_or_create_by(name: name) }
  end

  def all_tags
    return tags.collect(&:name).join(', ') if tags.present?
    ''
  end
end

当然我已经为文章指定了路线:

  resources :articles

当我使用“article_path”指定 url 时,我无法使用“new”操作(未指定 id),当我放置“articles”时,我无法修补(未找到 aciton)。我已经阅读了有关根据记录是新记录还是之前创建的记录来生成 url 和方法的信息,我也一直在考虑渲染部分内容。但我不太确定这些是否是正确的步骤。

标签: ruby-on-railsroutessimple-formsimple-form-for

解决方案


您可以检查您的对象是否是新记录,因此您可以为新表单或编辑表单指定不同的 url,如下所示:

= simple_form_for @article_form, 
url: (@article_form.new_record? ? your_path_for_new_record : your_path_for_edit) 
do |f|

希望这可以帮助。祝你好运!


推荐阅读