如何编写此Rails范围来检查中间表中的条件?

时间:2011-11-12 01:41:46

标签: ruby-on-rails ruby-on-rails-3.1

如何在User上编写一个范围,该范围返回与该用户关联的所有地址(通过订单),其中order.paid == true?

请注意,Order有多个关联的Address实例,名称不同,但Address模型是相同的。

class Order < ActiveRecord::Base
    belongs_to :shipping_address, :class_name => "Address", :foreign_key => :shipping_address_id
    belongs_to :billing_address, :class_name => "Address", :foreign_key => :billing_address_id
    belongs_to :user

    # the order table has a boolean 'paid' field
end

class Address < ActiveRecord::Base
    has_one :order
end

class User < ActiveRecord::Base
    has_many :orders
    # I want to create a scope here that returns addresses that belong to paid orders
end

1 个答案:

答案 0 :(得分:0)

如果我错了,请纠正我,但如果你添加了

 :has_many :addresses

到类订单,我认为它应该会让你回到与该用户相关的所有轨道。我只是在铁轨上学习红宝石,如果这是错误的,请道歉。