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
@referrals = Referral.select('id, company_id, (SELECT name FROM companies WHERE id = referred_to_id) AS name').where(company_id: 21)
In Rails you don't really need to worry about writing SQL like this. ActiveRecord handles the creation of all your simple SQL commands.
The code below will give you the company name so long as you have set up your relationships correctly in the models.
@referral = Referral.find(21)
@referral.company.name
See this tutorial on Active Record Associations
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With