用户使用has_many的两种类型的关联:through

时间:2013-02-02 21:56:58

标签: ruby-on-rails rails-activerecord

我有一个模特用户。用户可以拥有一个对象。用户还可以相互发送对象。我正在尝试访问用户的所有“发件人”,以便我可以访问@ user.senders并获取该用户的所有唯一发件人。这是我的设置:

class Object < ActiveRecord::Base
  belongs_to :user

  has_many :senders, through: :object_relationships, source: :user, class_name: "User"
  has_many :object_relationships
end

class User < ActiveRecord::Base
  has_many :owned_objects, inverse_of: :user

  has_many :objects, through: :object_relationships
  has_many :object_relationships
end

class ObjectRelationship < ActiveRecord::Base
  belongs_to :user
  belongs_to :object
end

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

class Gift < ActiveRecord::Base
  belongs_to :user

  has_many :gift_senders    
  has_many :senders, through: :gift_senders, source: :user
end

class User < ActiveRecord::Base
  has_many :sent_gifts, class_name: 'Gift', foreign_key: :user_id

  has_many :gift_senders    
  has_many :accepted_gifts, through: :gift_senders, source: :gift
end

class GiftSender < ActiveRecord::Base
  belongs_to :user
  belongs_to :gift
end

我已将您的模型重命名为礼物,以避免混淆。