【问题标题】:Using many-to-many nested models in Rails在 Rails 中使用多对多嵌套模型
【发布时间】:2009-11-17 00:03:52
【问题描述】:

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

我想要实现的是能够简单地定位客户的所有“工作”地址或“送货”地址。同时避免在连接表位置中重复文本

模型看起来像:

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")

【问题讨论】:

  • 我忽略了地址与位置的一对多关系。 Damien MATHIEU 的解决方案更接近于需要做的事情。

标签: ruby-on-rails activerecord


【解决方案1】:

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

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

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

【讨论】:

  • 这个方法是加到模型还是控制器上?将它放在模型上是有意义的,因为这是请求信息的来源
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-19
  • 1970-01-01
  • 2011-05-17
相关资源
最近更新 更多