1

레거시 시스템에 액세스하는 레일즈 애플리케이션을 구축 중입니다. 데이터 모델에는 하나 이상의 Subscription을 가질 수있는 Customers가 포함됩니다. Subscription은 항상 하나의 고객에게만 속합니다.레일즈와 액티브 레코드의 레거시 테이블과 비정규 화 된 연관

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가 포함된다는 것입니다. 따라서 고객 (최대 1 명)의 배열을 반환하는 Subscription에 연관성 "고객"을 원하지 않습니다. 고객과 연관된 관계를 반환하는 관계 "고객"을 실제로 원합니다.

조인 테이블 자체가 N : M 관계로 보이지만 ActiveRecord가이를 1 : N 관계로 만들 수있는 방법이 있습니까?

--Thomas

답변

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

고마워, 좋은, 간단한 제안! 유일한 단점 나는 "접근 방법"을 통해 할당 할 수 있다고 생각하지 않지만 아마도 관계가 항상 상대방으로부터 만들어 지는지 확인하는 것은 중요하지 않습니다. –

관련 문제