Circular relationship - habtm

So I have 2 models: Picture and Comment.

Pictures have many Comments, but I’d like for users to be able to post
Pictures in Comments, so Comments will have one Picture (possibly).
This creates a kind of circular relationship it looks like, and the
only way I could think of to implement this is with
has_and_belongs_to_many. Am I right, or is there a better way to do
this?

Hi –

On Sat, 3 Oct 2009, Mike C wrote:

So I have 2 models: Picture and Comment.

Pictures have many Comments, but I’d like for users to be able to post
Pictures in Comments, so Comments will have one Picture (possibly).
This creates a kind of circular relationship it looks like, and the
only way I could think of to implement this is with
has_and_belongs_to_many. Am I right, or is there a better way to do
this?

You could just do some judicious association naming – something like:

class Picture < AR::Base
has_many :comments
belongs_to :comment, :foreign_key => “illustration_id”
end

class Comment < AR::Base
belongs_to :picture
has_one :illustration, :class_name => “Picture”
end

That way, comment.picture = some_picture would always mean that this
comment belongs to that picture, while comment.illustration =
some_picture would mean that a given picture belonged to this comment.

Or… you could decide that the comment also belongs to the picture it
contains, with a distinct foreign key and so forth, though that might
feel a bit inside out.

David


David A. Black, Director
Ruby Power and Light, LLC (http://www.rubypal.com)
Ruby/Rails training, consulting, mentoring, code review
Book: The Well-Grounded Rubyist (The Well-Grounded Rubyist)