How can I write this query in Ruby on Rails? Query inside a select
SELECT id,
company_id,
(SELECT name
FROM companies
WHERE id = referred_to_id) AS name
FROM referrals
WHERE company_id = 21
How can I write this query in Ruby on Rails? Query inside a select
SELECT id,
company_id,
(SELECT name
FROM companies
WHERE id = referred_to_id) AS name
FROM referrals
WHERE company_id = 21
在 Rails 中,您真的不需要担心编写这样的 SQL。ActiveRecord
处理所有简单 SQL 命令的创建。
只要您在模型中正确设置了关系,下面的代码将为您提供公司名称。
@referral = Referral.find(21)
@referral.company.name
@referrals = Referral.select('id, company_id, (SELECT name FROM companies WHERE id = referred_to_id) AS name').where(company_id: 21)
@referral = Referral.joins(:company).select([:id,:company_id]).where(id: 21).first
然后使用
@referral.id
@referral.company_id
@referral.company.name
使用 activerecord,您可以通过以下方式实现:
referral = Referral.find(21)
referral.company.name
但是,如果您真的只想面对这些属性,则可以使用:
record = Referral.where("referrals.company_id = 21").joins("left join companies on referrals.referred_to_id = companies.id").select("referrals.id , referrals.company_id, companies.name as name").first
现在您可以访问该特殊对象的属性:
record.id
record.company_id
record.name