1

我正在构建一个访问遗留系统的Rails应用程序。数据模型包含可以具有一个或多个订阅的客户。订阅始终属于一个且仅有一个客户。Rails和ActiveRecord中遗留表的非标准化关联

Column   | Type | Modifiers 
-----------------+---------+----------- 
customer_id  | integer | not null 
subscription_id | integer | not null 

我有这个编码为两个客户一个has_and_belongs_to_many声明及认购

class Customer < Activerecord::Base 
    has_and_belongs_to_many :subscriptions, :join_table => "subscribes", 
    :foreign_key => "customer_id", :association_foreign_key => "subscription_id" 
end 
class Subscription < Activerecord::Base 
    has_and_belongs_to_many :customers, :join_table => "subscribes", 
    :foreign_key => "subscription_id", :association_foreign_key => "customer_id" 
end 
:虽然没有必要,这个关联是通过一个连接表“订阅”,它没有一个id列代表

我遇到的问题是,每个订阅只能有一个客户,而不是很多,并且连接表将始终最多包含一行,并带有特定的customer_id。 因此,我不希望关于返回一个(最多一个)客户数组的订阅的关联“客户”,我确实希望关联“客户”返回客户关联。

有没有办法强制ActiveRecord使它成为1对N关系,即使连接表本身似乎使它成为N对M关系?

- 托马斯

回答

1

我不知道,如果你能做到这一点与ActiveRecord,但如果你想任何办法解决这个问题,你可以在subscription模型定义customer方法:

class Subscription < Activerecord::Base 
    has_and_belongs_to_many :customers, :join_table => "subscribes", 
     :foreign_key => "subscription_id", 
     :association_foreign_key => "customer_id" 

    def customer 
     self.customers.first 
    end 
end 
+0

谢谢,好的,简单的建议!唯一的缺点我不认为我可以通过“访问方法”进行分配,但确保关系总是从另一方创建可能不是一个好主意。 – 2010-06-17 21:46:00