Rails: ActiveRecord query based on association value

Ruby on-RailsRubyActiverecordAssociations

Ruby on-Rails Problem Overview


I have 2 models. Report and Server that have a belongs_to and has_many relationship. I created an accessor method using delegate that allows a Report to find its associated Server.company_id. Now, I want to run a query on Report that allows me to find all Report that are associated with a specific Server that has a specific company_id attribute of 5.

Here are my two models. And yes I know the current query wont work since Report does not have an attribute company_id.

And no, I dont want to store company_id inside of Report since that information doesn't belong in Report.

Report

class Report < ActiveRecord::Base
  
 belongs_to :server

 delegate :company_id, :to => :server

 	class << self

	  	def method(url, base_url)
			#Report.where(company_id: 5)
	  	end
	end

end

Server

class Server < ActiveRecord::Base

 attr_accessible :company_id
  
 has_many :reports

end

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

You can perform a query like this:

Report.joins(:servers).where(:servers => {:company_id => 5})

To me, this is the cleaner solution to raw SQL.

Solution 2 - Ruby on-Rails

I'm using Rails 4.1.7 and the accepted answer did not work for me. What did work is

Report.joins(:server).where(:servers => {:company_id => 5})

Note that the difference is the key in the where clause is pluralized (:servers instead of :server)

Solution 3 - Ruby on-Rails

This should do the trick

Report.joins(:server).where('servers.company_id = ?', 5)

you could also add a scope for this like so

scope :with_company_id, lambda {|id| joins(:server).where('servers.company_id = ?', id) }

and then write

Report.with_company_id(5)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2158382View Question on Stackoverflow
Solution 1 - Ruby on-RailsKappaNossiView Answer on Stackoverflow
Solution 2 - Ruby on-RailsJoseph GillView Answer on Stackoverflow
Solution 3 - Ruby on-RailsPatrick OscityView Answer on Stackoverflow