Rails 3: Retrieve all child records where parent model attribute equals search key

前端 未结 1 1023
梦如初夏
梦如初夏 2021-02-08 15:47

I want to do a query that returns only the assets that do not have a serial number where the workorder branch equals a number.

class Workorder < ActiveRecor         


        
相关标签:
1条回答
  • 2021-02-08 16:33

    The query you would want to do is

    Asset.joins(:workorder).where('workorders.branch = 325')
    

    So you can make a scope like this:

    scope :with_workorder_branch, lambda { |branch| joins(:workorder).where('workorders.branch = ?', branch) }
    

    If you're going to be looping through the workorders, you should change the joins to includes as this eager loads them.

    The rails guide to queries is very helpful for this sort of thing http://guides.rubyonrails.org/active_record_querying.html

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