1

我在以下情况下遇到问题:用户可以在一家或多家公司工作,而一家公司可以有零个或多个用户在那里工作。对我来说,“捕获”是我需要跟踪哪些用户负责创建公司记录。

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

楷模

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

我必须如何处理才能创建公司记录(如果它不存在),在公司表中注册创建者的 *user_id* 并在工作表中创建关联?

这个想法是稍后创建一个表单,当前用户可以在其中选择他/她的工作地点(如果公司已经存在)或创建公司记录并注册协会。

4

0 回答 0