1

次のシナリオで問題が発生しています:ユーザーは 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* を登録し、worksテーブルに関連付けを作成するには、どのように処理すればよいですか?

アイデアは、後で現在のユーザーが自分の勤務先を選択できるフォームを作成するか (会社が既に存在する場合)、会社のレコードを作成して関連付けを登録することです。

4

0 に答える 0