Does ActiveRecord support the belongs_to association when saving the main object?

If I have two models:

class Post < ActiveRecord::Base belongs_to :user end 

and

 class User < ActiveRecord::Base has_many :posts end 

If I do this:

 post = Post.new user = User.new post.user = user post.save 

Is the user and primary key assigned in the post user_id field user_id ?

+7
ruby-on-rails activerecord associations
source share
3 answers

ActiveRecord belongs_to have the ability to autosave along with the parent model, but the functionality is disabled by default. To enable it:

 class Post < ActiveRecord::Base belongs_to :user, :autosave => true end 
+16
source share

I believe you want:

 class User < ActiveRecord::Base has_many :posts, :autosave => true end 

In other words, when saving a user post, find all the posts on the other side of the posts association and save them.

+7
source share

belong to the API documentation says (Rails 4.2.1):

:autosave

If true, always save the associated object or destroy it, if it is marked for destruction, while saving the parent object.

If false, never save or destroy the associated object.

By default, save only related objects if its a new record.

Note that accepts_nested_attributes_for sets: autosave to true.

In your case, the user is a new entry, so it will be automatically saved.

The last sentence about accepts_nested_attributes_for also been skipped by many.

0
source share

All Articles