Question

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 
Était-ce utile?

La solution 2

@referrals = Referral.select('id, company_id, (SELECT name FROM companies WHERE  id = referred_to_id) AS name').where(company_id: 21)

Autres conseils

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

@referral = Referral.joins(:company).select([:id,:company_id]).where(id: 21).first

Then use

@referral.id
@referral.company_id
@referral.company.name

Using activerecord you can achieve that by:

referral = Referral.find(21)
referral.company.name

But if you really want face those attributes only you can use:

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

Now you can access that special object's attributes as:

record.id
record.company_id
record.name
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top