我在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)
答案 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关系设置不正确。