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

后端 未结 3 1184
猫巷女王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:58

    You pass in an instance of the class you have defined. In your case, you would pass in a customer and then get the account.

    From the API http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

    Accessing the owner object

    Sometimes it is useful to have access to the owner object when building the query. The owner is passed as a parameter to the block. For example, the following association would find all events that occur on the user's birthday:

    class User < ActiveRecord::Base
      has_many :birthday_events, ->(user) { where starts_on: user.birthday }, 
        class_name: 'Event'
    end
    

    In your example it would be:

    class Customer < ActiveRecord::Base
      has_many :orders, ->(customer) { where(account_id: customer.account.id) }
    end
    

提交回复
热议问题