导轨的has_many:虽然STI [英] Rails has_many :though STI

查看:106
本文介绍了导轨的has_many:虽然STI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们开始与code,可能是这样的:

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

STI的部分,照片和握手之间的关联做工精细。问题是通过他的照片让所有用户的握手。

The STI part and associations between photos and handshakes work fine. The problem is getting all user's handshakes through his photos.

使用code以上的Rails显然会抱怨模型图片没有关联名为握手 。是否有AR任何设施,让我来说明这种关系?如果没有,你会写什么样的查询,让他们?

Using the code above Rails will obviously complain that model Photo does not have an association called handshakes. Is there any facility in AR that would allow me to specify a relation of this kind? If not, what query would you write to get them?

推荐答案

我最终使用下面的code,看上去像要解决这一问题的最简单的选择。

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

这篇关于导轨的has_many:虽然STI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆