Scaffolding table obtained by many-to-many relationship

3.9k views Asked by At

I have two models: User and Club and I have a many-to-may relationship like:

user has_and_belongs_to_many clubs
club has_and_belongs_to_many users

Now, I will have a third table with the result of this relationship:

user_clubs(user_id, club_id)

When generating scaffold, for example, rails generate scaffold User name:string birth_date:date gender:string login_id:integer, how can I generate that relationship? In the same way?

Thank you

2

There are 2 answers

1
mohameddiaa27 On

You need to use generate migration

rails g migration create_club_users user_id:integer club_id:integer

It will create the following migration:

class CreateClubUsers < ActiveRecord::Migration
  def change
    create_table :club_users do |t|
      t.integer :user_id
      t.integer :club_id
    end
  end
end

Then you should set id to false as in Create an ActiveRecord database table with no :id column?


I suggest that you read WHY YOU DON’T NEED HAS_AND_BELONGS_TO_MANY RELATIONSHIPS.

0
Choco On

You can try this:

rails g migration CreateClubsUsersJoinTable club_id:integer user_id:integer

You should follow alphabetical order of models when creating join table of has_and_belongs_to_many association in rails

Please refer this link for further assistance

http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many