Rails和Active Record STI猫狗各有一个好友,可以处理ActiveRelation



我正在尝试使用STI将树一侧的一个对象与另一侧的对象关联起来。我想做的事情如下。具体问题,我应该使用has_one,belongs_to吗?当一个更新到另一个看到这种关系时,还需要什么来实现它?

class Animal < ActiveRecord::Base
end
class Cat < Animal
  has_one :buddy # this is buddy_id, and has to be a dog
end
class Dog < Animal
  has_one :buddy # this should reference the other side? and should be a cat
end

只需使其中一个属于另一个,另一个将拥有第一个,假设cat是具有id字段的那个

class Cat < Animal
  belongs_to :buddy, class_name: Dog.name
end
class Dog < Animal
  has_one :buddy, class_name: Cat.name
end

最新更新