2015-10-27 39 views
1

我很難理解如何在涉及連接表時如何將關於俱樂部的所有者別名附加到用戶。我試圖建立一個應用程序,用戶可以創建一個俱樂部並將其他用戶添加到該俱樂部。活躍記錄擁有和屬於許多別名

用戶有很多俱樂部作爲所有者和屬於許多俱樂部作爲成員。

A俱樂部有很多用戶是成員和屬於 a用戶是它的主人。

我希望能夠得到以下信息:

user.clubs => Returns all clubs the User is a member of 
user.clubs_as_owner => Returns all the clubs they own 
club.owner => Returns the User Jane Doe 
club.members => Returns the Users: Jane D., Ashley K., Marry P. 

class User < ActiveRecord::Base 
    has_many :user_clubs 
    has_many :clubs, through: :user_clubs, :class_name => "Club", 
          :foreign_key => "member_id" 

    has_many :clubs_as_owner, through: :user_clubs, :class_name => "Club", 
            :foreign_key => "owner_id" 
end 

class Clubs < ActiveRecord::Base 
    has_many :user_clubs 
    has_many :members, through: :user_clubs, :class_name => "User", 
           :foreign_key => "user_id" 

    has_one :owner, through: :user_clubs, :class_name => "User", 
          :foreign_key => "user_id" 
end 

class UserClubs < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :club 
end 

回答

2

生成遷移:

def change 
    add_column :clubs, :user_owner, :integer # user id as owner 

    create_table :club_users, id: false do |t| 
     t.belongs_to :user, index: true 
     t.belongs_to :club, index: true 
    end 
    end 

並嘗試這樣的事:

class User < ActiveRecord::Base 
    has_and_belongs_to_many :clubs, 
          :class_name => 'Club', 
          :join_table => 'club_users', 
          :foreign_key => 'club_id', 
          :association_foreign_key => 'user_id' 
    def self.clubs_as_owner 
    Club.all.where('owner = ?', self.id) 
    end 
end 

class Clubs < ActiveRecord::Base 
    has_and_belongs_to_many :users, 
          :class_name => 'User', 
          :join_table => 'club_users', 
          :foreign_key => 'user_id', 
          :association_foreign_key => 'club_id' 
    def self.owner 
    User.find(self.user_owner) 
    end 
end 

club.users 
user.clubs 
user.clubs_as_owner 
club.owner 
0
#app/models/user.rb 
class User < ActiveRecord::Base 
    has_many :clubs_as_owner, class_name: "Club", foreign_key: :user_id 
    has_and_belongs_to_many :clubs, join_table: :memberships, foreign_key: :user_id, association_foreign_key: :clubs 
end 

#join table -- memberships - user_id | club_id 

#app/models/club.rb 
#columns id | owner_id | x | y | z | created_at | updated_at 
class Club < ActiveRecord::Base 
    belongs_to :owner, class_name: "User" 
    has_and_belongs_to_many :members, join_table: :memberships, foreign_key: :club_id, association_foreign_key: :user_id 
end 

這將允許您撥打:

@user = User.find x 
@user.clubs #-> all clubs user is a member of 
@user.clubs_as_owner #-> all clubs user is an owner of 

@club = Club.find x 
@club.members #-> all users with membership at club 
@club.owner #-> user who owns club