0

複数のモデルにアドレスが必要な複雑な関係があります。Rails:多態性1つのモデルに対して複数の関係が必要です。差別化の方法より良い方法がありますか?

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を導出し、多分このような何かを持っている必要があります場合、私は思ったんだけど:

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 

私もどのEventモデルを持っているので、これが行うには良いかもしれませんサイトアドレスが必要です。

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

関連する問題