A
A
Absolutely_Noob2019-12-23 17:38:13
PostgreSQL
Absolutely_Noob, 2019-12-23 17:38:13

How to properly set up habtm communication?

Good day
I have two models, Group and User

class Group < ActiveRecord::Base
     has_and_belongs_to_many :users
end

class User < ActiveRecord::Base
     has_and_belongs_to_many :groups
end

Migration
#rails g migration CreateJoinTableGroupsUsers groups users

class CreateJoinTableGroupsUsers < ActiveRecord::Migration
  def change
    create_join_table :groups, :users, id: false do |t|
      # t.index [:group_id, :user_id]
      # t.index [:user_id, :group_id]
    end
  end
end

This migration creates the following table:
create_table "groups_users", id: false, force: true do |t|
    t.integer "group_id", null: false
    t.integer "user_id",  null: false
  end

The essence of the problem: after creating a new group, I can see all the users inside it, but I can not reverse the process
Group.find(id).users #=> #<ActiveRecord::Associations::CollectionProxy [...users...]> 
User.find(id).groups #=> nil

Is it supposed to work both ways? How to do it right?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Absolutely_Noob, 2019-12-24
@Absolutely_Noob

I close the question, I replaced in the User model with
And now everything works as expected:
Problem solved.
It may have conflicted because of the word groups itself, because there is this https://apidock.com/rails/Rails/groups/class, but I'm not 100% sure

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question