Pierre-Louis Gottfrois
Pierre-Louis Gottfrois

Reputation: 17631

Confused by has_many and belongs_to associations

I'm a little bit confused here. I have 2 models: User Ticket

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

Answers (2)

hayesgm
hayesgm

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

Sohan
Sohan

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

Related Questions