# Link table logic

**URL:** <https://www.ruby-forum.com/t/link-table-logic/88665>\
**Category:** Rails\
**Created:** [March 13, 2007, 12:49pm UTC](https://www.ruby-forum.com/t/link-table-logic/88665 "2007-03-13T12:49:41Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![mick](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/f04885/32.png) [@mick](https://www.ruby-forum.com/u/mick)\
**Post date:** [March 13, 2007, 12:49pm UTC](https://www.ruby-forum.com/t/link-table-logic/88665/1 "2007-03-13T12:49:41Z")

</div>

Hi again! In my application, I have a Users model and an Events model. I  
also have a link model to link an event to a user. However, a user can  
be linked to an event in a number of ways - e.g. they can have created  
an event, or subscibed to an event.

Now, the link table for both these relationships will effectively  
contain the same information - an event ID and a user ID.

How is this link represented in the rails model?

For example, can I say:

class User \< ActiveRecord::Base  
has\_many :created\_events  
has\_many :subscribed\_events  
has\_many :events, :through =\> :created\_events, :subscribed\_events

or something to that effect? Also, how would User.events work in this  
case? The logic doesn’t seem quite correct!

Have I went about my database design in the wrong way?

As always, any help is greatly appreciated - I hope I have made myself  
clear!

Cheers,

Mick

---

<div class="post-metadata">

**Author:** ![mick](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/f04885/32.png) [@mick](https://www.ruby-forum.com/u/mick)\
**Post date:** [March 13, 2007, 12:58pm UTC](https://www.ruby-forum.com/t/link-table-logic/88665/2 "2007-03-13T12:58:00Z")

</div>

> case? The logic doesn’t seem quite correct!
> 
> Have I went about my database design in the wrong way?
> 
> As always, any help is greatly appreciated - I hope I have made myself  
> clear!

Untested, but fairly sure it will work:

Fetch the events for both relationships, then just add them:

def events  
cr\_ev=created\_events.events  
sb\_ev=subscribed\_events.events  
total = cr\_ev + sb\_ev  
total.uniq  
end

Best regards

Peter De Berdt

---

<div class="post-metadata">

**Author:** ![mick](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/f04885/32.png) [@mick](https://www.ruby-forum.com/u/mick)\
**Post date:** [March 13, 2007, 1:16pm UTC](https://www.ruby-forum.com/t/link-table-logic/88665/3 "2007-03-13T13:16:17Z")

</div>

Could a potential database design be as follows:

events - has unique event ID  
users - has unique user ID

user\_events - has event ID and user ID as a foreigh key

user\_event\_creation - has unique ID and user\_event\_id as foreign key  
user\_event\_subscription - has unique ID and user\_event\_id as foreign key

any ideas?
