【问题标题】:Non-normalized association with legacy tables in Rails and ActiveRecord与 Rails 和 ActiveRecord 中的旧表的非规范化关联
【发布时间】:2011-03-04 04:43:18
【问题描述】:

我正在构建一个访问旧系统的 Rails 应用程序。数据模型包含可以拥有一个或多个订阅的客户。订阅始终属于一个且仅一个客户。虽然不需要,但这种关联是通过一个连接表“subscribes”表示的,它没有 id 列:

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

我在 Customer 和 Subscription 中将此编码为 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

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

有什么方法可以强制 ActiveRecord 使其成为 1 对 N 关系,即使连接表本身似乎使其成为 N 对 M 关系?

--托马斯

【问题讨论】:

    标签: ruby-on-rails database activerecord normalization foreign-key-relationship


    【解决方案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
    

    【讨论】:

    • 谢谢,好的,简单的建议!唯一的缺点我认为我不能通过“访问方法”进行分配,但确保始终从另一方创建关系可能并不是什么大问题。
    猜你喜欢
    • 2012-01-10
    • 2012-12-31
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    • 2016-05-13
    • 2018-06-06
    • 2013-12-11
    相关资源
    最近更新 更多