How do you scope ActiveRecord associations in Rails 3?

后端 未结 6 1688
你的背包
你的背包 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:10

    If you're just trying to get the user's orders, why don't you just use the relationship?

    Presuming that the current user is accessible from the current_user method in your controller:

    @my_orders = current_user.orders
    

    This ensures only a user's specific orders will be shown. You can also do arbitrarily nested joins to get deeper resources by using joins

    current_user.orders.joins(:level1 => { :level2 => :level3 }).where('level3s.id' => X)
    

提交回复
热议问题