【发布时间】:2018-05-15 16:57:13
【问题描述】:
我试图找到以下问题的答案,但我失败了。
我正在使用表单对象创建 simple_form,但我不知道应该在 simple_form 中指定哪个 URL,以便为新操作和更新操作重用相同的表单。
这是我的代码: 文章控制器:
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 和方法的信息,我也一直在考虑渲染部分内容。但我不太确定这些是否是正确的步骤。
【问题讨论】:
-
simple_form文档似乎没有使用url选项。你确定要这样做吗? -
@jvillian 好吧,当我没有指定它时,它根本不起作用 - 这意味着我什至无法渲染表单,当我指定它时,如图所示,我得到了视图并且可以看到所有输入(即使我按下编辑,所有数据都是正确的),但我一次只能执行 1 个操作。如果那样的话,我不是 100%;就是这样,我只是在展示我目前的进步。编辑:它在这里被使用,例如:x0000ff.logdown.com/posts/245164-simple-form-and-bootstrap-3
标签: ruby-on-rails routes simple-form simple-form-for