【问题标题】:transform SQL query to rails query with many to many relations, what is the best practice?将 SQL 查询转换为具有多对多关系的 Rails 查询,最佳实践是什么?
【发布时间】:2020-08-23 08:22:23
【问题描述】:

您好,这是我的数据模型:

我想将此查询转换为 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

【问题讨论】:

  • 可能想要研究创建视图并基于它建立模型。
  • 感谢您的想法,我将分析执行此查询的频率。

标签: sql ruby-on-rails postgresql activerecord


【解决方案1】:

您可以使用连接将您需要的所有表连接在一起。 我假设你已经在你的模型中设置了所有的关系并且你的模型被命名为 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 })

【讨论】:

  • 谢谢!,但是结果没有携带状态字段,我认为这部分不起作用 Contactstatus.arel_table[:status],如果我运行这个: Contact.select(:id, Contactstatus.arel_table[:status]).joins(:contacts_lists, :contactstatuses).where(contacts_lists: { list_id: 1 }, contactstatuses: { company_id: 1 }),我得到:#<:relation id:>, #, #]>
  • 您在 ActiveRecord::Relation 输出中看不到它,但请尝试添加 .first.status。它应该在那里。它不是 Contact 模型的一部分,因此它不会出现在您的 ActiveRecord::Relation 输出中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-06
  • 2019-07-01
相关资源
最近更新 更多