下面是模型及其两个连接表:
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?
类似于这样的东西:
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发布于 2014-04-07 21:53:00
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记录的存在是表征语篇类型的唯一因素。
https://stackoverflow.com/questions/22923314
复制相似问题