relationship between tables

Remco Swoany wrote:

Abhi Manyu wrote:
  

Remco Swoany wrote:
    

Hi,

I have a users table(below) and now i want to create a new table
"occupation" so the users can fill in there occupation and store it in
the occupation-table.

Question: how can i realize a realionship between the users-table and
the occupation-table?

class CreateUsers < ActiveRecord::Migration
  def self.up
    create_table :users do |t|
      t.column :username, :string, :limit => 64, :null => false
      t.column :email, :string, :limit => 128, :null => false
      t.column :hashed_password, :string, :limit => 64
      t.column :enabled, :boolean, :default => true, :null => false
      t.column :profile, :text
      t.column :created_at, :datetime
      t.column :updated_at, :datetime
      t.column :last_login_at, :datetime
    end
    add_index :users, :username
  end

  def self.down
    drop_table :users
  end
end

Thanks..

Grtz..remco
      

Hi,
If a user is having many occupations
then you can give like
  has_many :occupations in CreateUsers
and
belongs_to :occupation,
               :class_name => "UserOccupation",
               :foreign_key => "user_occupation_id"

in Occupation table
    
Hi,

Thanks for you're quick reponse...

But must i add a column user_occupation_id in the users-table?

remco
  

Actually, if a user has many occupations, then the relationship will need to be modeled as a has_and_belongs_to_many (HABTM) and you will need to create a table called user_occupations_users table to model the many-to-many relationship. Search for has_and_belongs_to_many (HABTM) and you should be able to get enough to get started.

On the other hand, if a user can belong to only one occupation, then you need to add a table called occupations and in your user table, you need to occupation_id as an INT field. You can create a new migration that adds the column to the table. Then, user belongs_to occupation and occupation has_many users.

Cheers,
Mohit.
10/24/2007 | 4:58 PM.