首页 > 解决方案 > 将 SQL 查询转换为具有多对多关系的 Rails 查询,最佳实践是什么?

问题描述

嗨,这是我的数据模型:

在此处输入图像描述

我想将此查询转换为 activeRecord API

select c.id, c.name, c.phone, c.created_at,c.updated_at,s.status
from contacts c,contacts_lists cl, contactstatuses s
where cl.list_id = ? and s.company_id = ? and c.id = cl.contact_id and c.id = s.contact_id

最好的方法是什么?....这里的最佳做法是什么?,运行 sql plain 或使用 activeRecord API

标签: sqlruby-on-railspostgresqlactiverecord

解决方案


您可以使用连接将您需要的所有表连接在一起。我假设你已经在你的模型中设置了所有的关系并且你的模型被命名为 Contact、Contactstatus 和 ContactList。然后你应该能够构建一个像这样的查询:

select c.id, c.name, c.phone, c.created_at, c.updated_at, s.status
from contacts c
JOINS contacts_lists cl ON cl.contact_id = c.id
JOINS contactstatuses s ON s.contact_id = c.id
where cl.list_id = ? 
  and s.company_id = ?;

使用以下代码:

# I filled the id values (questionmarks) with a 1
Contact.select(:id, :name, :phone, :created_at, :updated_at, Contactstatus.arel_table[:status]).joins(:contacts_lists, :contactstatuses).where(contacts_lists: { list_id: 1 }, contactstatuses: { company_id: 1 })

推荐阅读