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?
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...
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? 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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With