【发布时间】:2011-01-18 03:11:55
【问题描述】:
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 多个不同的位置模型在应用程序/模型周围浮动?
【问题讨论】:
标签: ruby-on-rails single-table-inheritance