Q: Using Same Table in Multiple Associations

I'm having a brain cramp this morning. Here's what I want to do. I want users to log in, and then I want to use their log in name to track bugs they report and the person a bug is assigned to. That implies that a single model is associated with the same other model multiple times. Here's where the brain cramp comes in: I forgot how.

class Bug < ActiveRecord::Base   belongs_to :project   has_many :events   belongs_to :reporter # this is a :user   belongs_to :assigned_to # this is a :user   has_one :status

# ... end

The reporter and assigned_to associations have their own ids, reporter_id and assigned_to_id. However, these ids refer to records in the users table. I can create faux models Reporter and AssignedTo that do a set_table_name :users, but that wrecks all validations and other goodness. Is inheritance the right thing to do here?

Thanks

Hello s :slight_smile:     Eh, not a problem, brain cramps happen to the best of us :wink: The way -I- would change that bug class would be to have it look something like;

    class Bug < ActiveRecord::Base        belongs_to :user, :foreign_key => "reporter_id"        belongs_to :user, :foreign_key => "assigned_to_id"        ...     end

    Of course, this means in your bug table that you have to have two columns 'reporter_id' and 'assigned_to_id', but from what I have read, you already have those :wink: Btw, I am not going to even start asking 'what happens if you have more than one person helping on a bug' ;p

    Regards     Stef

s.ross wrote:

Stef T wrote:

Hello s :slight_smile:     Eh, not a problem, brain cramps happen to the best of us :wink: The way -I- would change that bug class would be to have it look something like;

    class Bug < ActiveRecord::Base        belongs_to :user, :foreign_key => "reporter_id"        belongs_to :user, :foreign_key => "assigned_to_id"        ...     end

This looks suspicious to me. You can't have two associations named user because then when you go @bug.user which user to do you want?

     class Bug < ActiveRecord::Base         belongs_to :reporter, :class_name=>'User', :foreign_key => 'reporter_id'         belongs_to :assignee, :class_name=>'User', :foreign_key => 'assigned_to_id'         ...      end

-Peter

Very good point Peter, I have never had the need to use the bug.user method, the place where in my application where I have a duplicate class, I only ever use the values stored using SQL in another application (reporting). Duly noted :slight_smile:

Regards Stef

petermichaux@gmail.com wrote: