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 多个不同的位置模型在应用程序/模型周围浮动?