Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 多态关联或属于关联_Ruby On Rails_Polymorphic Associations - Fatal编程技术网

Ruby on rails 多态关联或属于关联

Ruby on rails 多态关联或属于关联,ruby-on-rails,polymorphic-associations,Ruby On Rails,Polymorphic Associations,我在本例中使用多态关联: class Adress < ActiveRecord::Base belongs_to :addressable, polymorphic: true end class User < ActiveRecord::Base has_many :addresses, as: :addressable end 类地址

我在本例中使用多态关联:

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

class User < ActiveRecord::Base
  has_many :addresses, as: :addressable
end
类地址
我现在想要的是一个用户有一个家庭地址和一个工作地址。 我本可以:

class User < ActiveRecord::Base
  has_one :home_address, as: :addressable
  has_one :work_address, as: :addressable
end
class用户
但是我不知道哪一个是家庭住址,哪一个是工作地址


如何实现这一点?

如果您有一个
地址
表,请在
地址
表中保留一个字段为“
可寻址”
”。这样您就可以识别不同的地址

您可以在地址表中包含这些字段

t.integer :addressable_id
t.string  :addressable_type
或简化版本:

t.references :addressable, polymorphic: true

谢谢

您可以设置STI。您需要在地址模型中创建一个
类型

class Adress < ActiveRecord::Base

end

class WorkAddress < Address
   belongs_to :user
end

class HomeAddress < Address
   belongs_to :user
end

class User < ActiveRecord::Base
  has_one :work_address
  has_one :home_address
end
类地址
是的,但是可寻址类型对我没有帮助,因为它保存的是类“User”。无论如何,感谢您的帮助。addressable_type是在多态关系中存储关联对象类的字段的标准名称。您应该添加另一个字段,称为“类别”或其他内容,它可以存储“工作”、“家庭”、“移动”等。在我看来,这是一个非常好的解决方案。我试试看。谢谢,伙计:)@GustavoLobo没问题。如果这是适合你的答案,那么请接受它为正确。非常感谢!这不起作用,因为它实际上保存在表地址上的是类用户。无论如何,谢谢:)@GustavoLobo-您好,如果STI设置正确,它会将类名
工作地址
家庭地址
保存在
地址
表的
类型
列中。如果您想进一步聊天,我们可以在chat:)