gpt4 book ai didi

ruby-on-rails - Ruby on Rails - 如何委托(delegate)给多态关联?

转载 作者:数据小太阳 更新时间:2023-10-29 07:16:16 26 4
gpt4 key购买 nike

是否可以在多态模型中使用 delegatehas_manyhas_one 关联?它是如何工作的?

class Generic < ActiveRecord::Base
...

belongs_to :generable, polymorphic: true

delegate :file_url, to: :image, allow_nil: true
delegate :type_cat, to: :cat, allow_nil: true
end

class Image < ActiveRecord::Base
...
has_one :generic, as: generable, dependent: :destroy
end


class Cat < ActiveRecord::Base
...
has_one :generic, as: generable, dependent: :destroy
end

最佳答案

不确定这是否与您想要做的完全匹配,因为很难从您的示例中看出,但是...

class Generic < ActiveRecord::Base
...
belongs_to :generable, polymorphic: true
...
delegate :common_method, to: :generable, prefix: true
end

class Cat
def common_method
...
end
end

class Image
def common_method
...
end
end

允许您说以下内容:

generic.generable_common_method

关于ruby-on-rails - Ruby on Rails - 如何委托(delegate)给多态关联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13180710/

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