4

How can I handle a scenario where associated records may not be saved to the database?

If I have

class Blog < ActiveRecord::Base
  has_many :posts
end

class Post < ActiveRecord::Base
  has_many :comments
end

then adding an includes statement for eager loading throws away unsaved records:

blog = Blog.new
blog.posts << Post.new
blog.posts # => Return value contains one post
blog.posts.includes(:comments) # => Empty result

I could leave out the includes statement, but that'd mean slower code if my code interacted with comments and the blog and posts were saved.

I'm using Rails 4.1.

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338

0 Answers0