在Rails中使用多对多嵌套模型

时间:2009-11-16 12:22:51

标签: ruby-on-rails activerecord

我有以下情况设置来为具有多个地址的客户和地址类型的参考表建模。数据模型是 客户 - 地址:多对多关系,用名为“位置”的连接表表示 LocationType - 位置:一对多,因此locationtype(例如'work','home')可以与位置有很多关联。

我想要实现的是能够简单地找到客户的所有“工作”地址,或“交付”地址。虽然避免在连接表位置重复文本

模型如下:

class Address < ActiveRecord::Base
  has_many :locations  
  has_many :customers, :through => :locations  
end

class Customer < ActiveRecord::Base  
   has_many :locations  
   has_many :addresses, :through => :locations do  
   def special_location(loc)  
       find :all, :conditions => ['addr_type == ?', loc]  
   end  
  end  
end 

class Location < ActiveRecord::Base
    belongs_to :address
    belongs_to :customer
    belongs_to :locationtype
end

class LocationType < ActiveRecord::Base
    has_many :locations
end

这适用于以下简单案例:

@customer = Customer.find(1)  
@customer.addresses   # return all addresses

使用special_location(“string”)的'特殊辅助方法',我可以实现结果。我想知道的是如何通过使用附加参考表(LocationType)来实现相同的目标

的内容
@customer.addresses.find_locationtype("work")

1 个答案:

答案 0 :(得分:1)

您可以在选择请求中添加一些要加入的表。

def find_locationtype(type)
    find :all, :conditions => ['location_types.name = ?', type], :joins => :location, :locationtype
end

当您执行customer.find_locationtype('work')时,生成的查询将加入表格locationlocationtype。因此,您可以访问这两个表中的每个字段,并能够为它们添加条件。