Felix
Felix

Reputation: 5629

Rails adding table and relation

I've got a user table with all my users

Now I want to introduce user-groups

So I need a second table for the groups and a relation between those groups.

It should be possible to set a user in different groups. so I need a n:m relation

It read about that rails can generate most things I need and also generate the migration file? is that true? How does it works?

Migrations

class CreateUserGroups < ActiveRecord::Migration
  def up
    create_table :user_groups do |t|
      t.string :name
      t.integer :size

      t.timestamps
   end
  end

  def self.down
    drop_table :user_groups
  end
end


class CreateUserGroupUsers < ActiveRecord::Migration
  def self.up
    create_table :user_group_users do |t|
    t.user_id:integer
    t.user_groups_id:integer
    t.timestamps
  end
end

def self.down
    drop_table :user_group_users
 end

end

Upvotes: 0

Views: 59

Answers (1)

thedanotto
thedanotto

Reputation: 7327

Create your User and UserGroup model and migration from terminal

rails g model User email:string password:string
rails g model UserGroup name:string size:integer

You'll also want to create a UserGroup and User relationship managing table called UserGroupManager

rails g model UserGroupManager user_id:integer user_group_id:integer

Update your database by running this command in terminal

rake db:migrate

Set up the relationships within app/models/

# app/models/user.rb
class User < ActiveRecord::Base
  has_many :user_group_managers
  has_many :user_groups, through: :user_group_managers
end

# app/models/user_group.rb
class UserGroup < ActiveRecord::Base
  has_many :user_group_managers
  has_many :users, through: :user_group_managers
end

# app/models/user_group_manager.rb
class UserGroupManager < ActiveRecord::Base
  belongs_to :user_group
  belongs_to :user
end

Upvotes: 2

Related Questions