Yesterday’s Thoughts

August 30, 2011

Rails 3.1 Nested Associations

Some cool changes here: http://guides.rubyonrails.org/3_1_release_notes.html

Look at this one!

“Associations with a :through option can now use any association as the through or source association, including other associations which have a :through option and has_and_belongs_to_many associations.”

From the API Documentation (search for “Nested Associations”)


class Author < ActiveRecord::Base
  has_many :posts
  has_many :comments, :through => :posts
  has_many :commenters, :through => :comments
end

class Post < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :commenter
end

@author = Author.first
@author.commenters # => People who commented on posts written by the author

or equivalently


class Author < ActiveRecord::Base
  has_many :posts
  has_many :commenters, :through => :posts
end

class Post < ActiveRecord::Base
  has_many :comments
  has_many :commenters, :through => :comments
end

class Comment < ActiveRecord::Base
  belongs_to :commenter
end

The associations are read only:

When using nested association, you will not be able to modify the association because there is not enough information to know what modification to make. For example, if you tried to add a Commenter in the example above, there would be no way to tell how to set up the intermediate Post and Comment objects.

so you can’t do @author.commenters << Comment.new, but still this is a nice savings for some deeply nested associations that I’ve been dealing with lately.

Post a Comment