How do I make this association?

Ok, so to get this to work, I'll need to keep my foreign key names in the tickets table until I change them in my migration later. So I have this:

User: has_many :created_tickets, :class_name => "Ticket", :foreign_key => "created_by" has_many :opened_tickets, :class_name => "Ticket", :foreign_key => "opened_by"

Ticket: belongs_to :creator, :class_name => "User", :foreign_key => "creator_id" belongs_to :opener, :class_name => "User", :foreign_key => "opener_id"

In my view I'm still doing this: <%=h @ticket.created_by.username %>

But I'm still doing something wrong (undefined method error). Should I just go ahead and change the foreign key names in the tickets table to creator_id and opener_id? Thanks the help!

Hi --

Ok, so to get this to work, I'll need to keep my foreign key names in the tickets table until I change them in my migration later. So I have this:

User: has_many :created_tickets, :class_name => "Ticket", :foreign_key => "created_by" has_many :opened_tickets, :class_name => "Ticket", :foreign_key => "opened_by"

Ticket: belongs_to :creator, :class_name => "User", :foreign_key => "creator_id" belongs_to :opener, :class_name => "User", :foreign_key => "opener_id"

In my view I'm still doing this: <%=h @ticket.created_by.username %>

But I'm still doing something wrong (undefined method error). Should I just go ahead and change the foreign key names in the tickets table to creator_id and opener_id? Thanks the help!

I think it's just that Josh used creator and opener instead of created_by and opened_by as the association names. Try:

   @ticket.creator.username

Assuming that's OK, you can switch around as desired. Just keep them the same (i.e., the association name and the name of the method you call on @ticket).

David

Awesome. Thanks David. I think I've got the associations working now.

But I've also got one small hiccup from all this. My business logic is such that any new ticket will have a created_by and created_at field, but not necessarily an opened_at and opened_by field. So when I come to my ticket view after creating a new ticket and it hits <%=h @ticket.opener.username %>, I get the "You have a nil object when you didn't expect it!" error. Of course I don't get this error when the ticket has an opened_by value. So how do I avoid this? Am I supposed to check for nil before I try to display it? I've never had to do that before...is it because of this new association I've created?
Thanks again.