写真サイトがあるとします。作成者は、他の作成者からの更新を受け取るために購読できます。明らかに、著者 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明白な解決策は
- データベースの設計を変更し、「方向」という名前の列を追加します
- サブスクリプションが作成されるたびに 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'"
しかし、データベースの設計を変更せずに解決策があるのだろうか。