form_for()的多个参数

mai*_*aik 1 ruby-on-rails

我正在阅读Beginning Rails 3.它创建了一个博客,用户可以发布文章,也可以发表评论到这些文章.它们看起来像这样:

    class User < ActiveRecord::Base
      attr_accessible :email, :password, :password_confirmation
      attr_accessor :password

      has_many :articles, :order => 'published_at DESC, title ASC',
                          :dependent => :nullify
      has_many :replies, :through => :articles, :source => :comments

    class Article < ActiveRecord::Base
      attr_accessible :body, :excerpt, :location, :published_at, :title, :category_ids

      belongs_to :user
      has_many :comments

    class Comment < ActiveRecord::Base
      attr_accessible :article_id, :body, :email, :name
      belongs_to :article
Run Code Online (Sandbox Code Playgroud)

在app/views/comments/new.html.erb中有一个表单,其开头如下:

    <%= form_for([@article, @article.comments.new]) do |f| %>
Run Code Online (Sandbox Code Playgroud)

我的困惑在于为什么form_for()有两个参数.他们解决了什么,为什么有必要?

谢谢,迈克

Ern*_*est 16

实际上,在您的示例中,您form_for使用一个参数(即Array)进行调用.如果您查看文档,您将看到它所期望的参数:form_for(record, options = {}, &proc).在这种情况下,a record可以是ActiveRecord对象,也可以是Array(它也可以是像ActiveRecord一样嘎嘎叫的String,Symbol或对象).你什么时候需要传递一个数组呢?

最简单的答案是,当你有一个嵌套资源.在您的示例中,您已定义Article has many Comments关联.当您调用rake routes并且具有正确定义的路由时,您将看到Rails已为您定义了嵌套资源的不同路由,例如:article_comments POST /article/:id/comments.

这很重要,因为你必须为你的表单标签创建有效的URI(不是你,Rails为你做的).例如:

form_for([@article, @comments])
Run Code Online (Sandbox Code Playgroud)

你对Rails说的是:"嘿Rails,我给你作为第一个参数的对象数组,因为你需要知道这个嵌套资源的URI.我想在这个表单中创建新的注释,所以我会给你只是初始实例@comment = Comment.new.请为这篇文章创建这个评论:@article = Article.find(:id)."

这与写作大致相似:

form_for(@comments, {:url => article_comments_path(@aticle.id)})
Run Code Online (Sandbox Code Playgroud)

当然,还有更多的故事,但它应该足够,掌握这个想法.