Topic: has_many :through mixed with belongs_to

I'm having trouble with the following scenario:
- a user can work at one or more companies
- a company can have zero or more users working there
- company record must hold the user_id of the user that created the record

Migrations for the tables:

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :name

      t.timestamps
    end
  end
end

class CreateCompanies < ActiveRecord::Migration
  def change
    create_table :companies do |t|
      t.integer :user_id
      t.string :name

      t.timestamps
    end
  end
end

class CreateWorks < ActiveRecord::Migration
  def change
    create_table :works do |t|
      t.integer :user_id
      t.integer :company_id

      t.timestamps
    end
  end
end

Models:

class User < ActiveRecord::Base
  attr_accessible :name

  has_many :companies

  has_many :works
  has_many :companies, :through => :works

end

class Company < ActiveRecord::Base
  attr_accessible :name, :user_id

  belongs_to :user

  has_many :works
  has_many :users, :through => :works

end

class Work < ActiveRecord::Base
  attr_accessible :company_id, :user_id

  belongs_to :user
  belongs_to :company



end

How must I procced in order to create the company record (if it doesn't exist), register the user_id of the creator in company table and also create the association in works table?

The idea is later create a form where the current user can choose where he/she works (if the company already exists) or create the company record and register the association.

Thanks for any help or direction!  smile

Last edited by Moso (2012-06-27 10:18:08)

Re: has_many :through mixed with belongs_to

your post was truncated, please post it again. Thks

Re: has_many :through mixed with belongs_to

Hey Javix, post edited...  wink

Any ideas?  smile