中的实例变量与符号

中的实例变量与符号

本文介绍了ruby on rails (form_for) 中的实例变量与符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 ruby​​ on rails 的新手,并且正在 mac osx 上使用 2.3 版.我正在尝试创建脚手架创建的相同功能,但我自己.我创建了一个post"控制器、视图和模型.在后控制器中,我有以下内容:

i'm new to ruby on rails and am working with version 2.3 on mac osx.i am trying to create the same functionality a scaffold creates, but on my own.i created a "post" controller, view, and model.in post controller, i have the following:

class PostController < ApplicationController
  def index
  end

  def new
    @post = Post.new
  end
end

在 new.html.erb 中,我有以下内容:

in new.html.erb, i have the following:

<h1>New Post</h1>

<% form_for :post do |f| %>

    <%= f.text_field :title %>

<% end %>

我注意到在脚手架生成的代码中,form_for 助手使用了实例变量@post.如果在 form_for 中传递符号 :post 做完全相同的事情,而符号需要更改路由的配置,为什么他们在脚手架生成的表单中使用实例变量?

i noticed that in the scaffold generated code, the use the instance variable @post for the form_for helper. why do they use the instance variable in the scaffold generated form if passing the symbol :post in form_for does the exact same thing, while a symbol requires changing the config of the routes?

非常感谢,尤瓦尔

推荐答案

如果你使用符号 :post it created

if you use symbol :post it creates

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

如果你使用实例@post

if you use the instance @post

@post = Post.new 你会得到

for @post = Post.new you will get

<form action="/posts/create" class="new_account" id="new_account" method="post">

@post = Post.find(1) 你会得到

for @post = Post.find(1) you will get

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

如果您的新表格和编辑有不同的表格,但没有什么大不了的,但您的新表格更可能是相同或接近的

if you have different forms for your new and your edit no big deal but more likey than not your new and your edit forms are going to be identical or close to it

因此,如果您使用实例变量 @post,您可以将所有表单代码放入 _form 并调用部分代码,它会根据您传入新记录还是现有记录来处理其余部分

so if you use the instance variable @post you can put all the form code into _form and just call the partial and it will handle the rest based on if you pass in a new record or an existing record

这篇关于ruby on rails (form_for) 中的实例变量与符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 23:21