检测'键入'自我指涉协会

时间:2014-04-07 21:19:25

标签: ruby-on-rails activerecord

这是模型及其两个连接表:

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模型中,如何检测模型何时为replyretort

这些方面的东西:

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

这样我就可以做到以下几点:

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

1 个答案:

答案 0 :(得分:1)

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

我想这就是我的所作所为。因为我认为连接表记录的存在是表征话语类型的唯一因素。

相关问题