Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scaffolding table obtained by many-to-many relationship

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

like image 480
Silva_PT_SCP Avatar asked Oct 29 '25 17:10

Silva_PT_SCP


1 Answers

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.

like image 95
mohameddiaa27 Avatar answered Oct 31 '25 07:10

mohameddiaa27



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!