Ruby on rails RubyonRails中的实例变量与符号

Ruby on rails RubyonRails中的实例变量与符号,ruby-on-rails,Ruby On Rails,我是RubyonRails新手,正在MacOSX上使用2.3版。 我正在尝试创建与scaffold相同的功能,但是是我自己创建的。 我创建了一个“post”控制器、视图和模型。 在post controller中,我有以下内容: class PostController < ApplicationController def index end def new @post = Post.new end end <h1>New Post</h1&

我是RubyonRails新手,正在MacOSX上使用2.3版。 我正在尝试创建与scaffold相同的功能,但是是我自己创建的。 我创建了一个“post”控制器、视图和模型。 在post controller中,我有以下内容:

class PostController < ApplicationController
  def index
  end

  def new
    @post = Post.new
  end
end
<h1>New Post</h1>

<% form_for :post do |f| %>

    <%= f.text_field :title %>

<% end %>
class PostController
在new.html.erb中,我有以下内容:

class PostController < ApplicationController
  def index
  end

  def new
    @post = Post.new
  end
end
<h1>New Post</h1>

<% form_for :post do |f| %>

    <%= f.text_field :title %>

<% end %>
新职位
我注意到,在scaffold生成的代码中,使用实例变量@post作为表单_for helper。如果传递symbol:post-in-form\u for做了完全相同的事情,而symbol需要更改路由的配置,为什么他们在scaffold生成的表单中使用实例变量

多谢各位,
yuval

一个可能的原因是,它使表单创建新帖子的代码与表单更新现有帖子的代码更为相似。

如果使用symbol:post,则创建新帖子

<form action="/posts" method="post">

如果您使用实例@post

对于@post=post.new,您将获得

<form action="/posts/create" class="new_account" id="new_account" method="post">
<form action="/posts/update" class="edit_account" id="edit_account_1" method="post">
<input name="_method" type="hidden" value="put">

对于@post=post.find(1),您将获得

<form action="/posts/create" class="new_account" id="new_account" method="post">
<form action="/posts/update" class="edit_account" id="edit_account_1" method="post">
<input name="_method" type="hidden" value="put">

如果你的新表单和编辑表单不同,那没什么大不了的,但更可能的是,你的新表单和编辑表单是相同的或相近的


因此,如果您使用实例变量@post,您可以将所有表单代码放入表单中,只需调用partial,它将根据您传入的新记录或现有记录来处理其余部分

该隐藏方法的重要性在于浏览器不支持put和delete方法,因此您必须让应用程序知道何时发布方法意味着一个put或delete,谢天谢地,rails神奇地为我们处理了这个问题。您需要在新表单上使用@post,即使表单是分开的,您也需要它。否则,当您创建一个包含无效数据的新帖子时,它返回到包含验证错误的新表单时,它将不会填写您输入的信息。