【问题标题】:has_one :through polymorphic - is it possible?has_one :通过多态 - 有可能吗?
【发布时间】:2011-09-20 04:41:55
【问题描述】:

我的应用中有模型:

类注释<:base>

belongs_to :commentable, :polymorphic => true

结束

类项目<:base>

has_many :discussions, :dependent => :destroy
has_many :tickets, :dependent => :destroy

结束

课堂讨论<:base>

has_many :comments, :as => :commentable, :dependent => :destroy

结束

类票证<:base>

has_many :comments, :as => :commentable, :dependent => :destroy

结束

一切正常,但有时通过commentable(即comment.commentable.project)从评论中获取项目并不是很方便。 有没有办法在 Comment 模型中制作 has_one 项目?

【问题讨论】:

    标签: ruby-on-rails polymorphism has-one


    【解决方案1】:

    我会将以下方法添加到您的课程Comment

    def project
      self.commentable ? self.commentable.project : nil
    end
    

    这将为您提供相同的结果,而无需 ActivRecord 的所有魔力。

    【讨论】:

    • commentable.try(:project)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-03
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多