【问题标题】:Associate Rails active model with two different models将 Rails 活动模型与两个不同的模型相关联
【发布时间】:2017-07-12 10:51:46
【问题描述】:

有没有办法在 Ruby on Rails 活动模型中使用继承?

我有两个模型要添加 cmets。如果我可以只使用一个可以与两个模型相关联的 Comment 模型,那就太棒了。

【问题讨论】:

    标签: ruby-on-rails activerecord activemodel


    【解决方案1】:

    查看Polymorphic Associations

    class Comment < ApplicationRecord
      belongs_to :commentable, polymorphic: true
    end
    
    class Article < ApplicationRecord
      has_many :comments, as: :commentable
    end
    
    class Image < ApplicationRecord
      has_many :comments, as: :commentable
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 2010-10-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多