假设我们有一个摄影网站。任何作者都可以订阅以接收来自任何其他作者的更新。显然,如果作者 A 订阅了作者 B,这并不意味着 B 订阅了 A。所以我们建立模型
class Author < ActiveRecord::Base
has_many :subscriptions
has_many :subscribed_by_author, :through => :subscriptions, :source => :subscribed_to
end
class Subscription < ActiveRecord::Base
belongs_to :author
belongs_to :subscribed_to, :class_name => "Author", :foreign_key => "subscribed_to"
end
这样我们就可以使用
- some_author.subscribed_by_author -- some_author 订阅的作者列表。
- 对于任何订阅,我们都可以知道两端(谁订阅了谁)
但问题是如何仅使用rails(不使用普通SQL)获取订阅某个作者的人员列表,即得到答案:“谁订阅了some_author?”
问题:Rails 中是否有能力让双方的关系发挥作用,即不仅是写作some_author.subscribed_BY_author
,还有拥有some_author_subscribed_TO_author
?如果有,那是什么?
PS明显的解决方案是
- 更改数据库设计,添加名为“direction”的列
- 每次创建订阅时创建 2 条记录
添加到作者模型
has_many :subscribed_BY_author, :through => :subscriptions, :source => :subscribed_to, :conditions => "direction = 'by'"
has_many :subscribed_TO_author, :through => :subscriptions, :source => :subscribed_to, :conditions => "direction = 'to'"
但我想知道是否有不改变数据库设计的解决方案。