2012-04-30 82 views
3

我试图创建一个使用mongoid的嵌套属性的窗体。我的模型有以下代码:接受mongoid的嵌套属性约定

def Company 
    field :name 

    has_many :users, autosave: true, dependent: :destroy 
    accepts_nested_attributes_for :users 
end 

def User 
    belongs_to :company 
    has_one :profile 
end 

def Profile 
    belongs_to :user 
end 

是从形式返回的PARAMS是按以下顺序:

"company"=> 
    {"users_attributes"=> 
    {"0"=> 
     {"profile_attributes"=> 
     {"first_name"=>"123123abcd123", "last_name"=>"abcd123123123"}, 
     "email"=>"[email protected]", 
     "password"=>"123123123123", 
     "password_confirmation"=>"123123123123"}}, 
    "name"=>"abcd123123123", 
    "subdomain"=>"abcd123123123"} 

调用Company.create(PARAMS [:公司])似乎工作,但是它不正确地创建用户对象。当我做company.users时,我可以看到那个对象,但是当我做User.find时,那个文档不可用。读单证我意识到PARAMS应以下列方式进行传递:

"company"=> 
    {"users_attributes"=> 
    [{"profile_attributes"=> 
     {"first_name"=>"123123123", "last_name"=>"123123123"}, 
     "email"=>"[email protected]", 
     "password"=>"123123", 
     "password_confirmation"=>"123123"}], 
    "name"=>"abcd123123123", 
    "subdomain"=>"abcd123123123"} 

注意事项使用users_attributes,而不是一个散列数组的细微差别。这是正确的,但是它看起来并不像Active Record那样(以及它应该如何在rails中)。我不想采用params散列并修改数据以使其遵循某些约定。有没有更好的方法,我错过了什么?

回答

0

如果您可以命名将构成数组的inputs as user_attributes[]

所以不是有user_attributes[0][profile_attributes](我想你有这样的事情)

使其具有user_attributes[][profile_attributes]

0

你能张贴代码的形式?然后,我们可以开始研究它以某种方式进行格式化的原因。 (这应该是一条评论,但是我会在有更多关于这个问题的细节之后提供答案。)

在您的问题的旁边注释与视图中的窗体。我注意到你正在尝试创建一个公司,它是嵌套用户和用户,它也是嵌套的配置文件属性。如果您希望用户接受配置文件的嵌套属性,则需要将其放入用户模型中。

def User 
    belongs_to :company 
    has_one :profile, dependent: destroy, autosave: true 
    accepts_nested_attributes_for :profile 
end 

这可能解决您的问题,可能会从用户试图大众指定配置文件出现错误属性没有明确指示这样做。