How do I pass an argument to a has_many association scope in Rails 4?

后端 未结 3 1186
猫巷女王i
猫巷女王i 2021-01-31 03:24

Rails 4 lets you scope a has_many relationship like so:

class Customer < ActiveRecord::Base
  has_many :orders, -> { where processed: true }
e         


        
3条回答
  •  深忆病人
    2021-01-31 03:55

    The way is to define additional extending selector to has_many scope:

    class Customer < ActiveRecord::Base
       has_many :orders do
          def by_account(account)
             # use `self` here to access to current `Customer` record
             where(:account_id => account.id)
          end
       end
    end
    
    customers.orders.by_account(account)
    

    The approach is described in Association Extension head in Rails Association page.

    To access the Customer record in the nested method you just can access self object, it should have the value of current Customer record.

    Sinse of rails (about 5.1) you are able to merge models scope with the othe model has_many scope of the same type, for example, you are able to write the same code as follows in the two models:

    class Customer < ApplicationRecord
       has_many :orders
    end
    
    class Order < ApplicationRecord
       scope :by_account, ->(account) { where(account_id: account.id) }
    end
    
    customers.orders.by_account(account)
    

提交回复
热议问题