2010-09-22 136 views
4

我无法更新多级嵌套窗体中的数据。我使用partials来包含创建&更新视图的所有字段,并且我没有创建问题。只有更新。嵌套窗体&update_attributes

基本上具有结构(简化的)是:

user has_one profile 
profile has_many addresses 

form_for @user do |u| 
    u.fields_for :profile do |p| 
    p.fields_for :addresses do |a| 

就像我说,创建用户,配置文件和地址工作正常。只有当我尝试更新时才会发现问题。我没有收到错误,但实际上显示它已成功更新。它实际上确实正确更新了用户配置文件字段&,而不是地址字段。

这里是从堆栈跟踪更新的参数。 (再次,总结&格式化)

Parameters: {"controller"=>"profiles", "action"=>"update", "_method"=>"put", "id"=>"1", 
    "user"=>{"login" => "username", 
    "profile_attributes"=>{"first_name"=>"Admin", 
     "addresses_attributes"=>{ 
     "0"=>{"address"=>"123 Address Ave.", "city"=>"Cityville", "state"=>"CA"} 
     } 
    } 
    } 
} 

所有文件我能找到的只有1种显示嵌套形式,所以我不知道如果我使用正确的update_attributes超过1平深。

有什么想法?

+1

您是否使用'accepting_nested_attributes_for'方法? – DJTripleThreat 2010-10-06 20:36:56

+0

是的,我是。在我的个人资料模型中,我有accepted_nested_attributes_for:addresses,:allow_destroy => true – brewster 2010-10-13 01:47:23

+1

具有完全相同的问题。我使用rails v3.0.3和ruby 1.9.2p0。我感兴趣的是,如果有人使用2层或更多层次的嵌套不存在这个问题。 – SooDesuNe 2011-01-29 23:39:39

回答

1

我创建了一个名为cocoon的宝石,它可以帮助你。 它可以与标准Rails窗体,formtastic或简单窗体一起使用。

该gem可以使用多个嵌套级别。 github上的自述文件应该让你很容易地开始。如果您需要更多帮助,请告诉我。

6

您是否在模型中的任何位置使用attr_accessible,将允许进行批量分配的字段列入白名单?如果是这样,那么你会also need to add

attr_accessible :address_attributes 

,让这些属性将被传递给update_attributes

如果您尚未使用attr_accessible(或者它不推荐妹妹attr_protected)然后加入这一行,因为它会阻止所有疗法的属性被保存。

+0

不,在我的应用程序的任何地方都没有'attr_accessible'。 – SooDesuNe 2011-02-03 01:14:35

4

我遇到了类似的问题。在我的情况下,这是因为accept_nested_attributes_for类方法中的“reject_if”子句。

accepts_nested_attributes_for:播放器,:reject_if => PROC { |属性|属性[ 'FULL_NAME'。空白?}

通过在播放器的“full_name”属性中留下一个空字符串,Rails甚至不会尝试更新嵌套表单中存在的属性。在我的情况下,我意识到我不需要reject_if子句,所以我通过删除它来解决问题。

1

我在更新时也遇到同样的问题,而不是在创建。 我的类模型是讲座的has_many部件

class Lecture < ActiveRecord::Base 
    attr_accessible :name , :order , :html, :widgets_attributes 
    has_many :widgets 
    accepts_nested_attributes_for :widgets, :allow_destroy => true 
end 

class Widget < ActiveRecord::Base 
    belongs_to :lecture 
    attr_accessible :width, :height, :xpos, :ypos, :source 
end 

Widget类的最后一行使所有的差异。