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而不是字符串,因爲它可以使數據庫索引更小。在軌道上避免STI
我想象像下面這樣,但我不能完成的想法:
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聲明中的條件選項轉換爲等於1的類型。
我可以在視圖中的任何位置嵌入id這些字段出現,但這似乎也是錯誤的:
<%= f.hidden_field :type, LOCATION_TYPES[:location] %>
有什麼辦法來避免額外的子類或使LOCATION_TYPES方法的工作?
在我們的特殊情況下,應用程序是非常位置感知的,對象可以有多種不同類型的位置。我只是很奇怪,不想要所有這些子類?
任何建議,你有讚賞,告訴我我瘋了,如果你想,但你想看看10 +不同的位置模型漂浮在應用程序/模型?
您是對的,子類僅描述位置關係給用戶。 感謝您指向有關值對象與實體的文章。你是對的,用我現在的解決方案,我將最終複製位置表中的很多行。 不幸的是,價值對象的情況將不會解決,因爲位置模型實際上有更多的行爲,需要通過SQL訪問。 您的belongs_to方法似乎在頭部受到了攻擊,我不確定爲什麼我首先通過使用has_one來避免它。 – 2010-02-19 14:06:33