class User < ActiveRecord::Base
has_one :location, :dependent => :destroy, :as => :locatable
has_one :ideal_location, :dependent => :destroy, :as => :locatable
has_one :birthplace, :dependent => :destroy, :as => :locatable
end
class Location < ActiveRecord::Base
belongs_to :locatable, :polymorphic => true
end
class IdealLocation < ActiveRecord::Base
end
class Birthplace < ActiveRecord::Base
end
この状況でサブクラスを持つ理由が本当にわかりません。位置オブジェクトの動作は同じです。それらの唯一のポイントは、関連付けを簡単にすることです。また、データベースのインデックスを小さくできるため、データを文字列ではなく int として保存することをお勧めします。
私は次のようなものを想像していますが、考えを完成させることはできません:
class User < ActiveRecord::Base
LOCATION_TYPES = { :location => 1, :ideal_location => 2, :birthplace => 3 }
has_one :location, :conditions => ["type = ?", LOCATION_TYPES[:location]], :dependent => :destroy, :as => :locatable
has_one :ideal_location, :conditions => ["type = ?", LOCATION_TYPES[:ideal_location]], :dependent => :destroy, :as => :locatable
has_one :birthplace, :conditions => ["type = ?", LOCATION_TYPES[:birthplace]], :dependent => :destroy, :as => :locatable
end
class Location < ActiveRecord::Base
belongs_to :locatable, :polymorphic => true
end
このコードでは、次のことが失敗し、基本的に役に立たなくなります。
user = User.first
location = user.build_location
location.city = "Cincinnati"
location.state = "Ohio"
location.save!
location.type # => nil
has_one 宣言の :conditions オプションを 1 に等しい型に変換する方法がないため、これは明らかです。
これらのフィールドが表示されるビューのどこにでもIDを埋め込むことができますが、これも間違っているようです:
<%= f.hidden_field :type, LOCATION_TYPES[:location] %>
余分なサブクラスを回避したり、LOCATION_TYPES アプローチを機能させる方法はありますか?
私たちの特定のケースでは、アプリケーションは非常に位置を認識しており、オブジェクトはさまざまな種類の位置を持つことができます。これらすべてのサブクラスを必要としないのは奇妙ですか?
あなたが持っている提案は大歓迎です.もしあなたが望むなら私は狂っていると言ってください.しかし、あなたはアプリ/モデルの周りに浮かぶ10以上の異なる位置モデルを見たいですか?