# Circular relationship - habtm

**URL:** <https://www.ruby-forum.com/t/circular-relationship-habtm/176654>\
**Category:** Rails\
**Created:** [October 4, 2009, 3:47am UTC](https://www.ruby-forum.com/t/circular-relationship-habtm/176654 "2009-10-04T03:47:59Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![mikec](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/977dab/32.png) [@mikec](https://www.ruby-forum.com/u/mikec)\
**Post date:** [October 4, 2009, 3:47am UTC](https://www.ruby-forum.com/t/circular-relationship-habtm/176654/1 "2009-10-04T03:47:59Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![mikec](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/977dab/32.png) [@mikec](https://www.ruby-forum.com/u/mikec)\
**Post date:** [October 4, 2009, 4:03am UTC](https://www.ruby-forum.com/t/circular-relationship-habtm/176654/2 "2009-10-04T04:03:12Z")

</div>

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](http://www.rubypal.com))  
Ruby/Rails training, consulting, mentoring, code review  
Book: The Well-Grounded Rubyist ([The Well-Grounded Rubyist](http://www.manning.com/black2))
