Non-normalized association with legacy tables in Rails and ActiveRecord

Posted by Thomas Holmström on Stack Overflow See other posts from Stack Overflow or by Thomas Holmström
Published on 2010-06-15T20:48:39Z Indexed on 2010/06/15 20:52 UTC
Read the original article Hit count: 213

I am building a Rails application accessing a legacy system. The data model contains Customers which can have one or more Subscriptions. A Subscription always belong to one and only one Customer. Though not needed, this association is represented through a join table "subscribes", which do not have an id column:

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

I have this coded as a has_and_belongs_to_many declarations in both Customer and Subscription

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

The problem I have is that there can only ever be one customer for each subscription, not many, and the join table will always contain at most one row with a certain customer_id. And thus, I don't want the association "customers" on a Subscription which returns an array of (at most one) Customer, I really do want the relation "customer" which returns the Customer associated.

Is there any way to force ActiveRecord to make this a 1-to-N relation even though the join table itself seems to make it an N-to-M relation?

--Thomas

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about database