# How To Delegate to the Join Model?

**URL:** <https://www.ruby-forum.com/t/how-to-delegate-to-the-join-model/108704>\
**Category:** Rails\
**Created:** [July 6, 2007, 6:21am UTC](https://www.ruby-forum.com/t/how-to-delegate-to-the-join-model/108704 "2007-07-06T06:21:04Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![liquid](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/47e85d/32.png) [@liquid](https://www.ruby-forum.com/u/liquid)\
**Post date:** [July 6, 2007, 6:21am UTC](https://www.ruby-forum.com/t/how-to-delegate-to-the-join-model/108704/1 "2007-07-06T06:21:04Z")

</div>

Hi,

I’m wondering if someone can help me with this. I have a situation  
where I  
need to store information in the join model of a has\_many :through to  
assist  
with genearting views. But I can’t think of an elegant and efficient  
solution.

Heres an example of some code:

class Mailbox \< AR::B  
has\_many :mailbox\_contents  
has\_many :postcards, :through =\> ‘mailbox\_contents’  
end

class PostCard \< AR::B  
has\_many :mailbox\_contents  
has\_many :mailboxes, :through =\> ‘mailbox\_contents’  
end

class MailboxContent \< AR::B  
belongs\_to :mailbox  
belongs\_to :postcard  
end

So then I want to be able to have a default view for the post card in  
each  
mailbox.

to do this I put a column called default\_view into the MailboxContent  
model  
so that I can track default\_view per postcard inside each book.

This is because users share postcards. They can exist in multiple users  
mailboxes, and each user may want to see the image, or the text.

I came up with the following in the controller.

def index  
@mailbox = Mailbox.find( :include =\> :mailbox\_contents, :conditions =\>  
{  
:mailbox\_id =\> params[:mailbox\_id] } )  
@postcards = @mailbox.postcards  
end

And then in the view

\<% @postcards.each do |pc| %\>  
View Type  
\<%= @mailbox.mailbox\_contents.find\_by\_postcard\_id( postcard  
).default\_view  
%\>  
\<% end %\>

**shudder** Ugly

I would like to go the other way and use something like

postcard.default\_view

but I guess it would have to be postcard.default\_view\_for( @mailbox )

I guess the controller code would then change to

def index  
@mailbox = MailBox.find( paras[:id] )  
@postcards = @mailbox.postcards.find( :all, :include =\>  
[:mailbox\_contents] )  
end

Then in the postcard model

class Postcard AR::B  
def default\_view\_for( mailbox )  
self.mailbox\_contents.find\_by\_mailbox\_id( mailbox )  
end  
end

The question is, would doing this, eager loading in the controller, then  
accessing the collection in the model, prevent a whole heap of db  
requests  
in the view?

I’m hoping it will since I think the mailbox\_contents association should  
be  
cached for each model.

Any thoughts on a more elegant and or efficient way of doing this?

Cheers  
Daniel
