I have a tough time figuring out when associations are saved. I can of course refer to the associations guide, or test from the console each time (which is what I do), but is there a general underlying thumb rule that I can use?
For example:
class Blog < ActiveRecord::Base
has_many :posts
end
class Post < ActiveRecord::Base
belongs_to :blog
end
blog = Blog.create(name:‘My Travel Blog’)
post = Post.create(name: ‘My first post’)
blog.posts << post
is post’s blog_id field already updated in the database? or do I need to call post.save? Will blog.save work as well?
``
Perhaps there is an underlying principle, such as (this is only an example, it is not generally true) - associations are never saved without explicit call to save on the model that has a foreign key field.
@blog = Blog.create(name:'My First Blog')
@post = @blog.posts.create(name: 'My first post in My First Blog')
# post is now created and saved
@blog = Blog.find_by_name: 'My First Blog'
@post = @blog.posts.create(name: 'My second post in My First Blog')
# post is now created and saved
@blog = Blog.first
@post = @blog.posts.build(name: 'My third post in my My First Blog')
# post is being built but has not yet been saved
@post.save!
# post is now saved
Probably the easiest thing you can do is understand the types of methods
that are available to each object through their association.
Example (from rails console):
@blog = Blog.first
@blog.methods.sort.each do |method|
p method
end
Or, single line it for posts (just writing it different ways):