Alex Antonov
Alex Antonov

Reputation: 15216

How do I use accepts_nested_attributes_for and belongs_to?

I have a trouble with accepts_nested_attributes_for in Rails.

I have two models, User and UserCart:

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

and:

class User < ActiveRecord::Base
  has_one :user

When a user signs up, he creates the user cart too.

This is my view:

= 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

Why do I need to use this long and bad code to make user_cart fields fill-in after clicking the "Save" button, instead of a simple @user = User.new(permitted_params)?

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

Upvotes: 1

Views: 1839

Answers (1)

Philip7899
Philip7899

Reputation: 4677

Your user model should be:

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

class UserCart < ActiveRecord::Base
   belongs_to :user

Your belongs_to/has_one relationship was incorrectly setup.

Upvotes: 1

Related Questions