Rails: ActiveRecord query based on association value

前端 未结 4 370
耶瑟儿~
耶瑟儿~ 2020-11-30 00:08

I have 2 models. Report and Server that have a belongs_to and has_many relationship. I created an accessor method using delegate that

相关标签:
4条回答
  • 2020-11-30 00:50

    Server.where(company_id: 5).first.reports

    0 讨论(0)
  • 2020-11-30 01:03

    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)
    
    0 讨论(0)
  • 2020-11-30 01:04

    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)

    0 讨论(0)
  • 2020-11-30 01:06

    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.

    0 讨论(0)
提交回复
热议问题