gpt4 book ai didi

ruby-on-rails - 如何在 Rails 中通过继承获得多态关系?

转载 作者:行者123 更新时间:2023-12-03 09:11:53 25 4
gpt4 key购买 nike

我有以下 rails 模型。

class Service < ApplicationRecord
self.table_name ='service'
end

class ChildA < Service
has_many :charges
end

class ChildB < Service
self.table_name = "childb_table"
has_many :charges
end

class Charges < ApplicationRecord
:belongs_to chargeable, polymorphic: true
end
# code using this
a = ClassB.new.save
charge = Charges.new.save
a.charges.add(a) # this adds the column with the class name 'Service'

我尝试保存对象,但 chargeable_type 字段始终设置为基类 service 而不是子类。

我该如何解决这个问题?

最佳答案

您可以将 Service 类定义为抽象类。

使用 Rails 5.1 进行测试

class Service < ApplicationRecord
self.table_name ='service'
self.abstract_class = true
end

示例来自:http://www.rubydoc.info/docs/rails/4.0.0/ActiveRecord%2FInheritance%2FClassMethods%3Aabstract_class

class SuperClass < ActiveRecord::Base
self.abstract_class = true
end

class Child < SuperClass
self.table_name = 'the_table_i_really_want'
end

关于ruby-on-rails - 如何在 Rails 中通过继承获得多态关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41864653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com