[英]Rails has_many :though 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中是否有任何设施可以让我指定这种关系? 如果没有,您会写什么查询来获取它们?
您可以在User
中User
:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.