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

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

    I know this is old, but since no answer was accepted yet, I thought adding my views on the point would harm no one.

    The problem is that whenever you pass a scope to a has_many relationship, passing the instance of the owner class as an argument is not only a possibility but it is the only possibility to pass an argument. I mean, you are not allowed to pass more arguments, and this one will always be the instance of the owner class.

    So @RobSobers, when you

    "get all orders for account with an id of 1, seemingly arbitrarily."

    it is not arbitrary, you get all orders with th id of the customer you called the relation on. I guess your code was something like

    Customer.first.orders(@some_account_which_is_ignored_anyway)
    

    Seems like has_many relation was not meant to accept arguments.

    Personally, I prefer the solution of @МалъСкрылевъ.

提交回复
热议问题