Does accepts_nested_attributes_ work with belongs_to?

I get all kinds of conflicting information about this basic question, and the answer is pretty important for my current problems. So, is it very simple, in Rails 3 is it allowed or not to use accepts_nested_attributes_for with the own_to relation?

class User < ActiveRecord::Base belongs_to :organization accepts_nested_attributes_for :organization end class Organization < ActiveRecord::Base has_many :users end 

In view:

 = form_for @user do |f| f.label :name, "Name" f.input :name = f.fields_for :organization do |o| o.label :city, "City" o.input :city f.submit "Submit" 
+58
nested-attributes ruby-on-rails-3 belongs-to
Sep 09 '11 at 18:25
source share
4 answers

Nested attributes work fine for the belongs_to association, as does Rails 4. It may have been modified in an earlier version of Rails, but I tested it in 4.0.4, and it definitely works as expected.

+22
Apr 16 '14 at 16:29
source share

The names of the states of the epocwolf doc in the first line are "Nested attributes allow you to save the attributes of related records through the parent ." (my emphasis).

You might be interested in this other SO question that matches the same lines as this one . It describes two possible solutions: 1) moving accepts_nested_attributes to the other side of the relationship (in this case Organization) or 2) using the build method, create an Organization in the User before submitting the form.

I also found an essence that describes a potential solution for using accepts_nested_attributes with the own_to relation if you are ready to deal with a little extra code. It also uses the build method.

+21
Feb 28 2018-12-12T00:
source share

For the belongs_to association in Rails 3.2, the nested model needs the following two steps:

(1) Add a new attr_accessible to your child model (user model).

 accepts_nested_attributes_for :organization attr_accessible :organization_attributes 

(2) Add @user.build_organization to your User controller to create an organization column.

 def new @user = User.new @user.build_organization end 
+10
Apr 19 '14 at 7:49
source share

For Ruby on Rails 5.2.1

 class User < ActiveRecord::Base belongs_to :organization accepts_nested_attributes_for :organization end class Organization < ActiveRecord::Base has_many :users end 

Just got to your controller, suppose this is "users_controller.rb":

 Class UsersController < ApplicationController def new @user = User.new @user.build_organization end end 

And the view is the same as Nick did:

 = form_for @user do |f| f.label :name, "Name" f.input :name = f.fields_for :organization do |o| o.label :city, "City" o.input :city f.submit "Submit" 

In the end, we see that @ user3551164 has already been decided, but now (Ruby on Rails 5.2.1) we do not need attr_accessible :organization_attributes

+4
Aug 22 '18 at 13:53 on
source share



All Articles