# REST - Implementing HABTM in the real world

**URL:** <https://www.ruby-forum.com/t/rest-implementing-habtm-in-the-real-world/88526>\
**Category:** Rails\
**Created:** [March 12, 2007, 11:28am UTC](https://www.ruby-forum.com/t/rest-implementing-habtm-in-the-real-world/88526 "2007-03-12T11:28:08Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![tomtt](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/e47c2d/32.png) [@tomtt](https://www.ruby-forum.com/u/tomtt)\
**Post date:** [March 12, 2007, 11:28am UTC](https://www.ruby-forum.com/t/rest-implementing-habtm-in-the-real-world/88526/1 "2007-03-12T11:28:08Z")

</div>

Hi again - another REST question!

I think I’ve got a good grasp on it all now, except for how to  
implement HABTM properly. I understand you need turn the join model  
into a controller, such as ‘memberships’ below, and then use CRUD on  
that to perform joining actions.

class Group \< ActiveRecord::Base

has\_many :memberships  
has\_many :users, :through =\> :memberships

class User \< ActiveRecord::Base

has\_many :memberships  
has\_many :groups, :through =\> :memberships

class Membership \< ActiveRecord::Base

belongs\_to :user  
belongs\_to :group

What I don’t understand is how that actually works in your code. Let’s  
say I’m looking at all of the groups (GET /groups), and want to get  
the current user to join one. Presumably, I’d POST to /memberships?  
group\_id=1&user\_id=1.

But how would I handle if that failed, or they didn’t have permission  
to do so? And how would I handle the controller returning to the page  
it came from? Because I could hit the same action from both sides of  
the HABTM relationship. (User joining a group, and group selecting a  
user).

Are there any examples of this out there?

Thanks a lot!

Tom
