Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does ActiveRecord save a belongs_to association when saving 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:

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

Does the user get saved as well and the primary key properly assigned in post's user_id field?

like image 728
agentofuser Avatar asked Feb 09 '10 18:02

agentofuser


People also ask

What does ActiveRecord base do?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending. Edit: as Mike points out, in this case ActiveRecord is a module...

What is the difference between Has_one and Belongs_to?

They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user . To determine who "has" the other object, look at where the foreign key is.

What is ActiveRecord in Ruby on Rails?

What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.

What is polymorphic association in Rails?

Polymorphic relationship in Rails refers to a type of Active Record association. This concept is used to attach a model to another model that can be of a different type by only having to define one association.


2 Answers

ActiveRecord belongs_to associations have the ability to be autosaved along with the parent model, but the functionality is off by default. To enable it:

class Post < ActiveRecord::Base
  belongs_to :user, :autosave => true
end
like image 99
Josh Delsman Avatar answered Oct 19 '22 02:10

Josh Delsman


I believe you want:

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

In other words, when saving a User record, seek out all records on the other side of the 'posts' association and save them.

like image 28
cschille Avatar answered Oct 19 '22 02:10

cschille