简体   繁体   English

ActiveRecord通过关联进行多个联接

[英]ActiveRecord multiple joins through association

My customer model has many videos and videos has many video activities. 我的客户模型有很多视频,而视频有很多视频活动。

I want to join on video activities to limit based off videos that belong to a customer who has a specific email domain. 我想参加视频活动,以限制属于具有特定电子邮件域的客户的视频。

This code will give me all the video activities belonging to customer with id 52, but since videos don't have customer email, I need to join customer onto video and then do a .where. 此代码将为我提供ID为52的属于客户的所有视频活动,但是由于视频没有客户的电子邮件,因此我需要将客户加入视频,然后执行.where。

VideoActivity.joins(:video).where(videos: {customer_id: 52})

How is this done? 怎么做? Doing VideoActivity.joins(:video).joins(:customer) gives me an error saying VideoActivity doesn't have a customer associated with it. 进行VideoActivity.joins(:video).joins(:customer)给我一个错误,说VideoActivity没有与之关联的客户。

有很多方法可以完成此操作,并且所有方法都可以在大约同一位置结束,但是使用显式的where语句可以轻松实现此目标。

   VideoActivity.joins(:video).where("videos.customer_id = ?", 52)

VideoActiviy has no relation with customer, you need to say that the customer is related to the video, then it's easier to use active record's #merge that doing a hash where VideoActiviy与客户没有关系,你需要说的是,客户与视频,那么它更容易使用活动记录的#merge ,这样做的哈希where

VideoActivity.joins(video: :customer).merge(Customer.where('some condition'))

If you have a scope in videos you could use that too, here's an example 如果您在视频中有示波器,也可以使用它,这是一个示例

VideoActivity.joins(video: :customer).merge(Customer.some_scope)

PS: PS:

a scope could be 一个范围可能是

# customer model
scope :email_ends_with, ->(string) { where('email ilike ?', "%#{string}") }

Then use it 然后用

VideoActivity.joins(video: :customer).merge(Customer.email_ends_with('gmail.com'))

You can write plain sql to fetch records 您可以编写纯SQL来获取记录

activities = VideoActivity.joins('INNER JOIN videos ON video_activities.video_id = videos.id INNER JOIN customers ON videos.customer_id = customers.id')
activities.where('customers.email = ?', customer_email)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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