【问题标题】:Change type identifier in polymorphic association更改多态关联中的类型标识符
【发布时间】:2012-07-17 10:09:40
【问题描述】:

我正在尝试以一种有点奇怪的方式使用 Rails 的多态关联,但遇到了问题。

多态表是Address

class Address < ActiveRecord::Base
  belongs_to :addressable, polymorphic: true
end

我的数据库有唯一性约束,因此不能将相同的地址地址关联添加两次。

我还有一个需要两个地址的Trip 模型。一个是旅行的起点,另一个是目的地。

class Trip < ActiveRecord::Base
  has_one :origin, as: :addressable, class_name: 'Address'
  has_one :destination, as: :addressable, class_name: 'Address'
end

问题在于,当 Rails 创建与行程相关联的地址时,它使用类名(即“Trip”)来填充addressable_type 列。这意味着如果我尝试使用起点和终点进行旅行,rails 会尝试添加具有相同addressable_typeaddressable_id 的两行。这显然在唯一性约束上失败了。

我可以删除唯一性约束,但最终会得到重复的记录,这会使 Rails 感到困惑,因为它不知道哪条记录是起点,哪条记录是终点。

我真正想做的是指定用于addressable_type 的字符串:

class Trip < ActiveRecord::Base
  has_one :origin, as: :addressable, class_name: 'Address', type: 'Trip Origin'
  has_one :destination, as: :addressable, class_name: 'Address', type: 'Trip Destination'
end

这可能吗?是否有其他解决方案或者我需要重新考虑我的数据库架构?

【问题讨论】:

  • 为了后代,有可能吗?为什么这不可能?

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord polymorphism


【解决方案1】:

我原以为address 不应该belongs_to 一次旅行,因为一个地址可能是多次旅行的起点和/或目的地。如果您有唯一性约束,则尤其如此。外键应该存储在行程中:

class Address < ActiveRecord::Base
  has_many :trips_as_origin, class_name: "Trip", foreign_key: "origin_id"
  has_many :trips_as_destination, class_name: "Trip", foreign_key: "destination_id"
end

class Trip < ActiveRecord::Base
  belongs_to :origin, class_name: "Address"
  belongs_to :destination, class_name "Address"
end

您需要创建一个迁移,将origin_iddestination_id 添加到Trip

【讨论】:

  • 是的,这就是我自己怀疑的。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-11
  • 2011-10-16
  • 2019-09-23
相关资源
最近更新 更多