2013-02-24 19 views
7

W mojej aplikacji użytkownik może śledzić wielu użytkowników i może być śledzony przez wielu użytkowników. Próbowałem model używając asocjację has_and_belongs_to_manyRails Błąd łączenia HABTM

class User < ActiveRecord::Base 
    has_and_belongs_to_many :followers, class_name: "User", foreign_key: "followee_id", join_table: "followees_followers" 
    has_and_belongs_to_many :followees, class_name: "User", foreign_key: "follower_id", join_table: "followees_followers" 
end 

Także stworzyłem migrację do dołączenia tabeli w następujący sposób:

class FolloweesFollowers < ActiveRecord::Migration 
    def up 
    create_table 'followees_followers', :id => false do |t| 
     t.column :followee_id, :integer 
     t.column :follower_id, :integer 
    end 
    end 

    def down 
    drop_table 'followees_followers' 
    end 
end 

przy próbie dostępu do zwolenników użytkownika (User.first.followers) zgłasza błąd:

SQLException: no such column: followees_followers.user_id: SELECT "users".* FROM "users" INNER JOIN "followees_followers" ON "users"."id" = "followees_followers"."user_id" WHERE "followees_followers"."followee_id" = 1 

ja nie rozumiem, dlaczego jest ona dostępu followees_followers.user_id. Czy czegoś brakuje?

Odpowiedz

13

Opcje: foreign_key i :association_foreign_key są przydatne podczas konfigurowania łączenia wielu do wielu.

class User < ActiveRecord::Base 
    has_and_belongs_to_many :followers, class_name: "User", foreign_key: "followee_id", join_table: "followees_followers", association_foreign_key: "follower_id" 
    has_and_belongs_to_many :followees, class_name: "User", foreign_key: "follower_id", join_table: "followees_followers", association_foreign_key: "followee_id" 
end 
+1

Dzięki za link. Już działa –

2

Jest całkiem jasne, że spróbuje uzyskać dostęp do pola user_id, ponieważ uzyskujesz dostęp do relacji z instancji klasy User.

Spróbuj ustawić :association_foreign_key => "follower_id" w swoim związku followers i ustawić :association_foreign_key => "followee_id" w swoim związku followees.

+0

dzięki za odpowiedź. Zadziałało. –

Powiązane problemy