Non-normalized association with legacy tables in Rails and ActiveRecord
- by Thomas Holmström
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