Thursday, February 14, 2008

specialized collections using has_many

Here's the following scenario:

You have a ticketing system. You have a User that can create tickets. That same User can be assigned tickets. So how can you specify a has_many for both cases for the User?

Table Schema:

CREATE TABLE User
(
id INT,
title VARCHAR(42),
created_by INT,
assigned_to INT,
)




The answer:

class User
has_many :assigned_tickets, :foreign_key => 'assigned_to', :class => 'Ticket'
has_many :created_tickets, :foreign_key => 'created_by', :class => 'Ticket'
end



In action:
u = User.find(:first)

render :partial => 'tickets/assigned_tickets', :collection => u.assigned_tickets
render :partial => 'tickets/created_tickets', :collection => u.created_tickets

Labels:

1 Comments:

Blogger Russ Johnson said...

Ha ha! That looks familiar!! Thanks for helping me out with that Corey! I managed to get the relationship working all the way on both sides. I have the created_by being set in the controller on create and have even added an updated_by field that is being set in the controller on the update action. Its starting to come along nicely!

Thanks again for the help and sharing they ways of Ruby_Fu!

February 15, 2008 4:38 PM

 

Post a Comment

Subscribe to Post Comments [Atom]

<< Home