首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >自我参照联想类型的检测

自我参照联想类型的检测
EN

Stack Overflow用户
提问于 2014-04-07 21:19:25
回答 1查看 37关注 0票数 0

下面是模型及其两个连接表:

代码语言:javascript
复制
class Discourse < ActiveRecord::Base
    belongs_to :forum
    belongs_to :user

    has_many :impressions

    has_many :discourse_replies
    has_many :replies, through: :discourse_replies

    has_many :reply_retorts
    has_many :retorts, through: :reply_retorts
end

class DiscourseReply < ActiveRecord::Base
    belongs_to :discourse
    belongs_to :reply, class_name: 'Discourse', foreign_key: 'reply_id'
end

class ReplyRetort < ActiveRecord::Base
    belongs_to :reply
    belongs_to :retort, class_name: 'Discourse', foreign_key: 'retort_id'
end

Discourse模型中,如何检测模型是reply还是retort

类似于这样的东西:

代码语言:javascript
复制
class Discourse < ActiveRecord::Base
    # removed relationships for brevity       

    def is_discourse?
        # if instance is a discourse, return true else false
    end


    def is_reply?
        # if instance is a reply, return true else false
    end

    def is_retort?
        # if instance is a retort, return true else false
    end
end

这样我就可以做以下几件事:

代码语言:javascript
复制
2.0.0p247 :004 > discourse = Discourse.create
 => #

2.0.0p247 :001 > reply = discourse.replies.create
 => #

2.0.0p247 :005 > retort = reply.retorts.create
 => #

2.0.0p247 :006 > retort_retort = retort.retorts.create
 => #

2.0.0p247 :007 > discourse.is_discourse? #=> true
2.0.0p247 :007 > reply.is_reply? #=> true
2.0.0p247 :007 > retort.is_retort? #=> true
2.0.0p247 :007 > retort_retort.is_retort? #=> true
2.0.0p247 :007 > retort_retort.is_reply? #=> false
2.0.0p247 :007 > retort_retort.is_discourse? #=> false
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-04-07 21:53:00

代码语言:javascript
复制
class Discourse < ActiveRecord::Base
    # removed relationships for brevity       

    def is_discourse?
        !is_reply? && !is_retort?
    end

    def is_reply?
        DiscourseReply.where(reply_id: id).any?
    end

    def is_retort?
        ReplyRetort.where(retort_id: id).any?
    end
end

我想这就是我要做的。因为我认为join记录的存在是表征语篇类型的唯一因素。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22923314

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档