Ser*_*iuk 5 database-design ruby-on-rails has-many belongs-to
假设我们有一个摄影网站.任何作者都可以订阅以接收来自任何其他作者的更新.显然,如果作者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
Run Code Online (Sandbox Code Playgroud)
这样我们就可以使用了
但问题是如何获得仅使用rails(不使用普通SQL)订阅某些作者的人员列表,即得到答案:"谁订阅了some_author?"
问题:Rails中是否有任何能力使双方的关系工作,即不仅写作some_author.subscribed_BY_author而且有some_author_subscribed_TO_author?如果有一个,那么它是什么?
PS明显的解决方案是
添加到作者模型
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""
但我想知道是否有一个解决方案而不改变数据库设计.
# Author model
has_many :subscriptions_to, :class_name => "Subscription", :foreign_key => "subscribed_to"
has_many :subscribed_to_author, :through => :subscriptions_to, :source => :author
Run Code Online (Sandbox Code Playgroud)
据我所知 - 它有效!:)