0

여러 모델에 주소가 필요한 복잡한 관계가 있습니다.레일 : 다형성 한 모델에 여러 번 관계가 필요합니다. 차별화하는 방법? 더 좋은 방법이 있습니까?

a = Account.first 
a.billing_address #returns an address 
a.site_address #returns the same address 

가 어떻게 계정이 두 주소를 구별 얻을 수 ... 이것이 함께 문제

class Address < ApplicationRecord 
    belongs_to :addressable, polymorphic: true 
end 

class User < ApplicationRecord 
    # no issue, its "addressable" so just use this line of code 
    has_one :address, as: :addressable 
end 

class Account < ApplicationRecord 
    # Ok the issue here is that I need exactly TWO addresses though 
    # One is for billing and one if a physical address where an event will 
    # physically take place. 
    has_one :billing_address, class_name: "Address", as: :addressable 
    has_one :site_address, class_name: "Address", as: :addressable 
end 

: 이것은 보통과 같이 다형성 관계를 사용하는 것을 의미? 나는 이것이 실제로 다형성의 한계가 아니라 오히려 해결해야 할 소프트웨어 설계 문제라는 것을 알고 있습니다. 어쩌면 내가 추상적 인 모델로 Address을 치료하고 그것에서 BillingAddressSiteAddress을 유도 어쩌면 같은 것을 가질 필요가 있는지 궁금 해요 : 나는 또한 Event 모델을 가지고 있기 때문에

class Address < ApplicationRecord 
    # see active_record-acts_as gem for how this mixin works 
    # https://github.com/hzamani/active_record-acts_as 
    actable 
    belongs_to :addressable, polymorphic: true 
end 

class User < ApplicationRecord 
    # no issue, its "addressable" so just use this line of code 
    has_one :address, as: :addressable 
end 

class BillingAddress < ApplicationRecord 
    acts_as :address 
end 

class SiteAddress < ApplicationRecord 
    acts_as :address 
end 

class Account < ApplicationRecord 
    has_one :billing_address 
    has_one :site_address 
end 

이 할 좋은 수 있습니다을하는 사이트 주소가 필요하므로 다음을 수행하십시오.

class Event < ApplicationRecord 
    has_one :site_address 
end 

공학적입니까? 지나치게 주관적인 소리를 낼 위험이 있습니다. 이것에 대한 당신의 생각은 무엇입니까? 이 작업을 수행하는 더 좋은 방법이 있습니까?

답변

0

주소 카테고리를 구분하는 것은 무엇입니까? 청구서 수신 주소와 사이트 주소가있을 수 있습니다. 예를 들어, 카테고리는 당신이해야 할 모든이 주소에 관계 선언에 조건을 설정 한 후 '카테고리'이라는 속성에 의해 결정되는 경우

:

class Account < ApplicationRecord 
    has_one :billing_address, -> { where category: 'billing' }, class_name: "Address", as: :addressable 
    has_one :site_address, -> { where category: 'site' }, class_name: "Address", as: :addressable 
end 
+0

내가 좋아하는 그것을해야 할 수도 있습니다 이. 이벤트 및 계정에 사이트 주소가 있고 계정에 청구서 수신 주소가 있고 사용자가 일반 주소 만 가지고 있기 때문에 부울 필드가 작동하지 않지만 카테고리 필드가 없으므로 카테고리 필드가 없습니다. 감사! – DJTripleThreat