简体   繁体   English

Rails has_many:尽管STI

[英]Rails has_many :though STI

Lets start with code that may go like this: 让我们从可能如下的代码开始:

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

The STI part and associations between photos and handshakes work fine. STI部分以及照片和握手之间的关联正常。 The problem is getting all user's handshakes through his photos. 问题在于通过用户的照片获得所有用户的握手。

Using the code above Rails will obviously complain that model Photo does not have an association called handshakes . 使用上面的代码,Rails显然会抱怨模型Photo没有称为handshakes的关联。 Is there any facility in AR that would allow me to specify a relation of this kind? AR中是否有任何设施可以让我指定这种关系? If not, what query would you write to get them? 如果没有,您会写什么查询来获取它们?

You could use in User : 您可以在UserUser

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

I understand this works as is you had: 我了解这和您的做法一样有效:

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

Obviously handshakes method does not exist in submitted_photos, but AR made this for you by joining tables. 显然握手方法在submitted_photos中不存在,但是AR通过连接表为您做到了这一点。

I ended up using the following code, looked like an easiest option to solve this problem. 我最终使用了以下代码,看起来像是解决此问题的最简单方法。

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.

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