Rails has_many:虽然是STI

让我们从代码开始,可能是这样的:

class User < ActiveRecord::Base has_many :photos has_many :submitted_photos has_many :posted_photos has_many :handshakes, through: :photos end class Photo < ActiveRecord::Base belongs_to :user end class PostedPhoto < Photo has_many :handshakes, inverse_of: :poster, foreign_key: 'poster_id' end class SubmittedPhoto < Photo has_many :handshakes, inverse_of: :submitter, foreign_key: 'submitter_id' end class Handshake < ActiveRecord::Base belongs_to :submitter, class_name: 'SubmittedPhoto' belongs_to :poster, class_name: 'PostedPhoto' end 

STI部分和照片与握手之间的关联工作正常。 问题是让所有用户通过他的照片握手。

使用上面的代码Rails显然会抱怨模型Photo没有称为handshakes的关联。 AR中是否有任何设施允许我指定这种关系? 如果没有,你会写什么查询来获取它们?

您可以在UserUser

 has_many :submitted_handshakes, through: :submitted_photos, source: :handshakes has_many :posted_handshakes, through: :posted_photos, source: :handshakes 

我明白这就像你有的一样:

 user.submitted_handshakes ----> user.submitted_photos.handshakes 

显然握手方法在submitted_photos中不存在,但是AR通过连接表为你做了这个。

我最终使用以下代码,看起来是解决此问题的最简单方法。

 class User def handshakes Handshake.where('submitter_id IN (?) OR poster_id IN (?)', submitted_photo_ids, posted_photo_ids) end end