Reputation: 17631
I'm a little bit confused here. I have 2 models: User Ticket
A Ticket belongs to one User as "assigned".
A User has many Tickets (twice ?)
So here what I've got:
# Table name: tickets
#
# id :integer not null, primary key
# label :string(255)
# content :text
# reported_by_id :integer
# assigned_to_id :integer
# created_at :datetime
# updated_at :datetime
#
class Ticket < ActiveRecord::Base
belongs_to :reported_by, :class_name => 'User'
belongs_to :assigned_to, :class_name => 'User'
end
# Table name: users
#
# id :integer not null, primary key
# login :string(255)
# password :string(255)
# created_at :datetime
# updated_at :datetime
#
class User < ActiveRecord::Base
has_many :tickets, :class_name => 'Ticket', :foreign_key => 'reported_by_id'
has_many :tickets, :class_name => 'Ticket', :foreign_key => 'assigned_to_id'
end
I would like to do "aUser.tickets" and get all user's tickets that he reported.
Any help ? Thx !
Upvotes: 0
Views: 583
Reputation: 9096
You should differentiate the names of your has_many in your User model:
class User < ActiveRecord::Base
has_many :reported_by_tickets, :class_name => 'Ticket', :foreign_key => 'reported_by_id'
has_many :assigned_to_tickets, :class_name => 'Ticket', :foreign_key => 'assigned_to_id'
end
Now call
@user.reported_by_tickets
@user.assigned_to_tickets
Otherwise, your code looks right on target.
Upvotes: 1
Reputation: 3807
Basically, you need to different properties for two different relations and a third method that combines the two.
class User < ActiveRecord::Base
has_many :reported_tickets, :class_name => 'Ticket', :foreign_key => 'reported_by_id'
has_many :assigned_tickets, :class_name => 'Ticket', :foreign_key => 'assigned_to_id'
def tickets
reported_tickets + assigned_tickets
end
end
Upvotes: 1