複数のモデルにアドレスが必要な複雑な関係があります。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
を治療し、それからBillingAddress
とSiteAddress
を導出し、多分このような何かを持っている必要があります場合、私は思ったんだけど:
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
エンジニアリングはこれですか?あまりにも主観的な響きの危険で、これについてのあなたの考えは何ですか?これを行うより良い方法はありますか?
私は次のようにそれをしなければならないかもしれませんこの。イベントとアカウントにはサイトアドレスがあり、アカウントには請求先住所があり、ユーザーは通常のアドレスしか持たないので、ブールフィールドは使えませんが、カテゴリフィールドはありません。ありがとう! – DJTripleThreat