Вопрос

I'm actually trying to create a has_many through association. Let me first explain a bit about how things are supposed to work.

I have a users, groups and members tables. The rules are as follow :

  • A user can create a group (depending on it's role) (groups table has a user_id)
  • A user can be member of one or many groups (members table contain user_id and group_id)

Here is my current relationship classes :

class User < ActiveRecord::Base
  # Associations
  has_many :groups # As user, I create many groups
  has_many :members
  has_many :groups, through: :members # But I can also belongs to many groups
end

class Group < ActiveRecord::Base
  # Associations
  belongs_to :user
  has_many :members
  has_many :users, through: :members
end

class Member < ActiveRecord::Base
  # Associations
  belongs_to :user
  belongs_to :group
end

My problem is about the group relationship. You see a user can create groups, which means :

has_many :groups

but a user can also be member of groups :

has_many :groups, through: :members

Because of this new relationship, 75% of my specs are now broken. Also, I notice that if I logged in with a user associated to a group, I can see actually groups list. But when I'm trying to logged in as group owner (the one who created the group), I can not see the groups created by that user).

Idea?

Это было полезно?

Решение

You are not looking for an has_many through relationship here

Try that :

class User < ActiveRecord::Base
  # Associations
  has_and_belongs_to_many :groups
  has_many :created_groups, class_name: 'Group', foreign_key: 'creator_id'
end

class Group < ActiveRecord::Base
  # Associations
  belongs_to :creator, class_name: 'User'
  has_and_belongs_to_many :members, class_name: 'User'
end

This is a solution if you don't need the member class to do any special treatment. You should have a migration that looks like that:

class CreateGroupsUsers < ActiveRecord::Migration
  def change
    create_table :groups_users, id: false do |t|
        t.references :group
        t.references :user
    end
    add_index :groups_users, [:group_id, :user_id]
    add_index :groups_users, :user_id
  end
end

And you have to make sure that your groups table have a creator_id !

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top