2010-07-19 52 views
0

尝试执行一个嵌套对象窗体。该页面加载没有错误,但是当我发送它时,没有信息被保存到组织模型中。另一个导轨嵌套窗体问题

SQL调用说这个..

Parameters: {"commit" => "save", "action"=>"update","_method"=>"put", "organization"=>{"likes_snacks"=>"0"}, .. 

这是正确的。通过打开和关闭复选框可以正确更改1和0。但是,我猜这些信息并没有保存到数据库中。有任何想法吗?

HAML:

- form_for @user do |f| 
    = f.label :username 
    = f.text_field :username 
.clear 
    - fields_for :organization do |org| unless @user.organizations.empty? 
    = org.label :likes_snacks, 'Like snacks?' 
    = org.check_box :likes_snacks 
= f.submit 'save', {class => 'button'} 

CONTROLLER:

def edit 
    @user = current_user 
    @organization = current_user.organizations.first 
end 

模型:

ORGANIZATION.RB:

has_many :users, :through => :organizations_users 

USER.RB:

has_many :organizations, :through => :organizations_users 
+0

如果你可以张贴'user'和'organization'型号代码也更好。 – randika 2010-07-19 16:53:29

+0

f.text_field:username是否保存到数据库? – 2010-07-19 16:55:20

+0

@jesse是的它确实 – Trip 2010-07-19 17:02:18

回答

2

看起来好像你可以保存父属性而不是子属性。

为了让孩子通过属性的嵌套形式的访问,你需要将“#{} CHILD_CLASS_NAME _attributes”添加到你的父类的方法attr_accessible(只有使用attr_accessible在父模型)

所以你父模型应该是这样的:

class User < ActiveRecord::Base 
    attr_accessible :username, :organizations_attributes 
    accepts_nested_attributes_for :organizations 
end 

另外,如果你没有在你的父模型使用attr_accessible这是没有必要的。

+0

我在用户模式下不使用attr_accessible。你是否说我在我的模型中不需要它? – Trip 2010-07-19 17:34:54

+0

Yah ..为什么会:用户名与organizational_attributes连接,或者更具体地说,为什么用户的一个属性属于organizational_attributes? – Trip 2010-07-19 17:39:42

+0

啊gotcha。我忘记了。这工作!感谢Randika – Trip 2010-07-19 18:50:18

1

我认为这里有趣的部分是链接器表:organization_users。

对这个问题如此的接受的答案说,你需要

form_for @user do |f| 
    f.fields_for :organization_users do |ff| 
    ff.fields_for :organization 
+0

啊!那么..在fields_for帮助之前添加f。但我得到这个返回作为错误.. 未知属性:organization_users 当我尝试它我的旧方法我得到这个 未知属性:组织 – Trip 2010-07-19 18:26:57

+0

使用“field_for:组织”(其复数),它返回此ActiveRecord :: UsersController中的AssociationTypeMismatch#update Organization(#24980000)expected,got Array(#101190) – Trip 2010-07-19 18:29:08

+0

你在做“ff.fields_for:organization”---我认为double ff修复了期望问题。 – 2010-07-19 18:53:46