积极记录拥有并归属于许多别名

时间:2015-10-27 20:53:58

标签: ruby-on-rails activerecord

我很难理解如何在涉及联接表时将所有者的别名附加到与俱乐部相关的用户。我试图建立一个应用程序,用户可以创建一个俱乐部,并将其他用户添加到该俱乐部。

用户拥有多个俱乐部作为所有者,属于许多俱乐部作为会员。

俱乐部拥有许多用户,其成员是属于作为其所有者的用户。

我希望能够获得以下信息:

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 个答案:

答案 0 :(得分:4)

生成迁移:

  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

答案 1 :(得分: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