How do you scope ActiveRecord associations in Rails 3?

后端 未结 6 1745
你的背包
你的背包 2021-01-30 01:21

I have a Rails 3 project. With Rails 3 came Arel and the ability to reuse one scope to build another. I am wondering if there is a way to use scopes when defining a relationsh

6条回答
  •  不要未来只要你来
    2021-01-30 02:02

    How about association extensions?

    class Item < ActiveRecord::Base
      has_many :orders do
        def for_user(user_id)
          where(user_id: user_id)
        end
      end
    end
    
    Item.first.orders.for_user(current_user)
    

    UPDATE: I'd like to point out the advantage to association extensions as opposed to class methods or scopes is that you have access to the internals of the association proxy:

    proxy_association.owner returns the object that the association is a part of. proxy_association.reflection returns the reflection object that describes the association. proxy_association.target returns the associated object for belongs_to or has_one, or the collection of associated objects for has_many or has_and_belongs_to_many.

    More details here: http://guides.rubyonrails.org/association_basics.html#association-extensions

提交回复
热议问题