我如何使用accepts_nested_attributes_for和belongs_to?

时间:2013-12-25 13:19:56

标签: ruby-on-rails ruby nested-attributes strong-parameters

我在Rails中遇到accepts_nested_attributes_for的问题。

我有两个型号,User和UserCart:

class User < ActiveRecord::Base
  belongs_to :user_cart
  accepts_nested_attributes_for :user_cart

class User < ActiveRecord::Base
  has_one :user

当用户注册时,他也会创建用户购物车。

这是我的观点:

= form_for @user, as: :user, url: users_path, html: { class: 'forms forms-columnar' } do |f|
  p
    = f.label :email
    = f.email_field :email, class: 'width-100'
  .user_cart
    = f.fields_for :user_cart do |user_cart_field|
      p
        = user_cart_field.label :inn
        = user_cart_field.text_field :inn

为什么在点击“保存”按钮而不是简单的user_cart后,我需要使用这个长而不好的代码来填充@user = User.new(permitted_params)个字段?

@user = User.new
@user.build_user_cart
@user.assign_attributes(permitted_params)

1 个答案:

答案 0 :(得分:1)

您的用户模型应为:

class User < ActiveRecord::Base
   has_one :user_cart
   accepts_nested_attributes_for :user_cart

class UserCart < ActiveRecord::Base
   belongs_to :user

您的belongs_to / has_one关系设置不正确。