【发布时间】: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