为什么controller中的new action需要初始化实例变量?

Why does the new action in the controller need the instance variable initialized?

为什么controller中的new action需要初始化实例变量@article?我已经测试过,在新操作中没有实例变量的情况下,一条记录可以很好地保存到数据库中的表中。

class ArticlesController < ApplicationController
  def new
    @article = Article.new
  end

  def create
    @article = Article.new(article_params)

    if @article.save
      redirect_to @article
    else
      render 'new'
    end
  end
end

创建模型的空实例的目的是基于这样的想法,即新视图与编辑视图共享大量视图代码,因此需要模型继续工作。

例如,在许多情况下,新页面和编辑页面几乎相同。您文章的新页面可能允许用户输入姓名、作者和发布日期。现在用户可能希望编辑此信息,您可能会向他们显示完全相同的三个文本字段,用于编辑名称、作者和发布日期。

要彻底解决这个问题(不要重复自己),您可以将该表单组合到一个视图部分中。您最终会得到这样的视图:

# new.html.haml
New Article
= render :partial => "form"

# edit.html.haml
Edit Article
= render :partial => "form"

# _form.html.haml
= text_field_tag "title", @article.title
= text_field_tag "author", @article.author
= text_field_tag "publishing_date", @article.publishing_date

显然,当您编辑现有文章时,您需要从数据库中获取该数据,然后使用其属性来填写表单。许多人所做的是在他们的新页面中重用该表单,但现在该表单期望有一个 @article 变量,因此程序员在他们的 new 操作中初始化一个空变量。

如果您的部分表单需要调用对象的方法,这也会有所帮助。例如:

# article.rb
def published_today?
  return (self.publishing_date.to_date == Date.today)
end

# _form.html.haml
- if @article.published_today?
  %strong New!

但是如果您的新页面和编辑页面不共享相同的代码,并且您的新页面不需要创建空模型实例,那么请不要打扰,没关系。