を形成する二つの側の"多対多関係のレール?
-
20-09-2019 - |
質問
あるとしましょう写真のサイトです。他の著者に加入することが可能で更新を受信その他の。う場合は著者が加入稿るこのロマンティックホテえてくるということではない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は当社
- みの購読を知ることができるので両者が加入者)
がどのように使うかを取得のリストをご契約の一著者のみを使用レールを使用しない平野SQL i.eの答え"が加入some_author?"
質問はありま能力のレールを取得し、関係職両面にわな執筆 some_author.subscribed_BY_author
が有する some_author_subscribed_TO_author
?その場合、その後は?
P.S.って、ソリューション
- 変更データベースのデザインをするときには付加されない"方向性"
- を2記録時のご契約の作成
追加の著者モデル
has_many:subscribed_BY_author,通=>:契約数:source=>:subscribed_to,条件=>"direction='に'"
has_many:subscribed_TO_author,通=>:契約数:source=>:subscribed_to,条件=>"direction='を'"
そして、もうひとつがある場合は液を変えずにデータベースのデザイン。
解決
# Author model
has_many :subscriptions_to, :class_name => "Subscription", :foreign_key => "subscribed_to"
has_many :subscribed_to_author, :through => :subscriptions_to, :source => :author
私の知る限りでは - それは働きます! :)
他のヒント
私はこのような単純なもののために、プレーンHABTMを使用したいが、あなたはどんな結合テーブルを必要としないとしている。
create_table :subscriptions do |t|
t.column :author_id, :integer
t.column :subscriber_id, :integer
end
それをポイント著者:
class Author < ActiveRecord::Base
has_and_belongs_to_many :subscribers
:class_name => "Author",
:join_table => "subscriptions",
:association_foreign_key => "subscriber_id"
def subscriptions # "subscribers" is already included above
self.subscribers.find(:all, :subscriber_id=>author.id) # hopefully not too
end # much SQL
end
あなたが本当にあなたのメソッド名にコミットしている場合:
def subscribed_to_author
subscribers
end
def subscribed_by_author(author)
self.subscribers.find(:all, :subscriber_id=>author.id)
end
いくつかの接続を作成します(私はSubscriptionsControllerはRESTyであることを作ると思います)。
SubscriptionsController < ApplicationController
def create
@author = Author.find(params[:author_id] # author to be subscribed to
@user = current_user # user clicking the "subscribe" button
@author.subscribers << @user # assuming authors should only
@author.save # be able to subscribe themselves
end
end
表示名、または任意の
@author.subscribers.each do |s|
s.name
end
# ...or...and...also...
<%= render :partial => @author.subscribers -%>
<%= render :partial => @author.subscriptions -%>
所属していません StackOverflow