当form_for使用符号时,fields_for不起作用 [英] fields_for doesnt working when form_for use symbol

查看:95
本文介绍了当form_for使用符号时,fields_for不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个form_for代码

i have a form_for code

<%form_for :a,:url=>{:controller=>"biz/a",:action=>"save"},:html =>{:multipart => true} do |f| %>
.....
<%f.fields_for :b do |b|%>
.....
<%b.fields_for :apples  do |apple|%>
...
<%end%>
....
<%end%>

它输出不带fields_for函数的html代码

it outputs the html code without fields_for function

<textarea cols="40" id="a_b_apples_content" name="a[b][apples][content]" rows="20" style="width:500px;height:100px;border:1px #889BAA solid;color:#999;font-size:12px;padding:6px;"></textarea>

当我将form_for更改为:

when i change the form_for to :

<%form_for @a,:url=>{:controller=>"biz/a",:action=>"save"},:html =>{:multipart => true} do |f| %>

它工作正常. 它输出:

it just work fine. And it outputs:

<textarea cols="40" id="a_b_apples_content" name="a[b_attributes][apples_attributes][0][content]" rows="20" style="width:500px;height:100px;border:1px #889BAA solid;color:#999;font-size:12px;padding:6px;"></textarea>

如我所愿. 为什么form_for中的符号不​​能正常工作?form_for中的:a和@a有什么区别? 谢谢. 我使用rails 2.3.8,ruby 1.8.7,chrome网络浏览器.

as i want. why dont the symbol in form_for work fine?what's difference between :a and @a in form_for. Thanks. I use rails 2.3.8 , ruby 1.8.7,chrome web browser.

推荐答案

这是造成挫败感的常见原因. form_for实际上根据您将符号或对象传递给它的方式而有所不同.如果您将其传递给符号,就像这样:

This is a common source of frustration. form_for actually behaves differently based on whether you pass it a symbol or an object. If you pass it a symbol, like so:

<% form_for :person do |f| %>
  <% f.text_field :name %>
<% end %>

然后,表单生成器将起作用,但是它将仅设置参数值,并在存在@person的情况下加载默认值.您的帕尔马哈希看起来应该像这样:

Then the form builder will work, but it will only setup the param values, and load the default values if @person exists. Your parmas hash will look like it should:

params = {
  :person => {
    :name => 'bob'
  }
}

但是它无法正确设置您的路线.假设您要提交到已经打开过的同一页面.现在,如果给它一个对象,form_for将为您做更多的事情.它将检查该对象是否是新对象或正在更新,并将相应地设置form标记的参数,以及其他一些好处.

But it won't setup your route properly. It'll assume you want to submit to the same page you're already on. Now if you give it an object, form_for will do much more for you. It will check to see if this object is new, or being updated, and it will set the form tag's parameters accordingly, along with some other benefits.

老实说,我不能告诉你为什么他们的行为有所不同.符号版本显然仍然可以访问实例变量(在上面的示例中为@person),因为这些字段将使用其现有值填充.一种简单的解决方案是传递实例变量始终是正确的方法,并且可以正常工作.

Honestly, I can't tell you why they behave differently. The symbol version obviously still has access to the instance variable (@person in the example above) because the fields will be populated with their existing values. The easy solution is that passing an instance variable is always the way to go, and will work correctly.

这篇关于当form_for使用符号时,fields_for不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆