Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How i can write a query inside select in rails

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 
like image 422
kashif Avatar asked Oct 29 '25 18:10

kashif


2 Answers

@referrals = Referral.select('id, company_id, (SELECT name FROM companies WHERE  id = referred_to_id) AS name').where(company_id: 21)
like image 123
Marek Lipka Avatar answered Oct 31 '25 07:10

Marek Lipka


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

like image 45
Dan Grahn Avatar answered Oct 31 '25 09:10

Dan Grahn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!