简体   繁体   中英

Confused by has_many and belongs_to associations

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

  • A Ticket belongs to one User as a "reporter".
  • 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 !

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM