2010-02-14 4 views
5

사진 사이트가 있다고 가정 해 보겠습니다. 모든 작성자는 다른 작성자로부터 업데이트를 받기 위해 구독 할 수 있습니다. 제작자 A가 B가 A에 가입되어 의미하지 않는다 저자 B에 가입 분명히한다면 우리는 우리가Rails에서 "양면"다 대다 관계를 만드는 방법은 무엇입니까?

  1. some_author.subscribed_by_author를 사용할 수있는 모델

    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이 구독하는 저자의 (일반 SQL을 사용하지 않는) 우리 둘 (누구에 가입) 끝

하지만 문제는 레일을 사용하여 일부 저자에 가입 한 사람들의 목록을 받으시는 방법을 알 수있는 가입에 대한

  • 즉 GET "some_author에 누가 가입 했습니까?"

    질문 : 레일스에서 ​​관계가 양립 할 수있는 능력이 있습니까? 즉, some_author.subscribed_BY_author을 쓰고 있지만 some_author_subscribed_TO_author을 쓰는 것입니까? 하나 있다면, 그것은 무엇입니까?

    P. subscribed_BY_author :

  • 2를 만들기 확실한 해결책이라는 이름의 열을 추가,

    1. 변경 데이터베이스 설계하는 것입니다 "방향은"가입이
    2. 저자 모델

      has_many에 추가 생성 될 때마다 기록 : through => : subscriptions, : source => : subscribed_to, : conditions => "by direction"by

      has_many : subscribed_TO_author : : through :> : 구독 : 소스 :> 구독하기 : : condit ion => "direction = 'to' '"

    그러나 데이터베이스 설계를 변경하지 않고도 해결책이 있는지 궁금합니다.

  • 답변

    0
    # Author model 
    has_many :subscriptions_to, :class_name => "Subscription", :foreign_key => "subscribed_to" 
    has_many :subscribed_to_author, :through => :subscriptions_to, :source => :author 
    

    내가 아는 한 - 작동합니다! :)

    +0

    불행히도 그렇지 않았습니다.하지만 그것은 올바른 방향과 다음 코드가 작동했습니다. #Author model has_many : subscriptions_to, : class_name => "Subscription", : foreign_key => "subscribed_to" has_many : subscribed_to_author, : through :> : subscriptions_to, : source => : 작성자 나는이 대답을 받아 들인다. 그러나 먼저 정확한 것으로 편집해야한다. 고마워! –

    +0

    항상 내 승무원을 고치는 것은 나의 큰 즐거움이다 :) – klew

    2

    나는 이처럼 단순한 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 -%> 
    
    +0

    고마워! 그것은 매우 도움이되었습니다. 이제 문제를 해결하는 두 가지 방법을 찾았습니다. –

    +0

    @Sergii, 그건 내가 에릭의 방식대로 우위에 서서 삭제 한 나의 대답에 대해 말하고 있었던 것이다. –

    관련 문제