철도에서“양측”다중 관계를 만드는 방법은 무엇입니까?
-
20-09-2019 - |
문제
사진 사이트가 있다고 가정 해 봅시다. 모든 저자는 다른 저자로부터 업데이트를 받기 위해 구독 할 수 있습니다. 저자 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가 구독 한 저자 목록.
- 구독의 경우 양쪽 목적을 알 수 있습니다 (누가 구독 한 사람)
그러나 문제는 레일 만 사용하여 일부 저자에게 구독 한 사람들의 목록 (일반 SQL을 사용하지 않음)을 얻는 방법입니다. 즉, "누가 Some_author에 가입 되었습니까?"
질문 : 철도에 관계가 일할 수있는 능력이 있습니까? 양측은 글쓰기뿐만 아니라 some_author.subscribed_BY_author
그러나 some_author_subscribed_TO_author
? 하나 있다면 무엇입니까?
PS 명백한 해결책은 다음과 같습니다
- "Direction"이라는 열을 추가하여 데이터베이스 설계를 변경합니다.
- 구독이 생성 될 때마다 2 개의 레코드를 만듭니다
저자 모델에 추가하십시오
has_many : subscribed_by_author, : through => : subcriptions, : source => : subscribed_to, : 조건 => "direction = 'by'by '"
has_many : subscribed_to_author, : through => : subscriptions, : source => : subscribed_to, : 조건 => "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
내가 아는 한 - 그것은 작동합니다! :)
다른 팁
나는 이와 같은 간단한 것을 위해 일반 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 < 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 -%>