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