0

I have to tables that have a many to many relationship. I have created the correct table codesecure_project_tst_definition and it works. I can join rows together by calling the codesecure_projects << method on a TstDefinition object. The problem is that for some reason active record wants to use Codesecure_project_id as the id value for the codesecure_project_tst_definition table. What am I doing wrong? How do I fix it so that when I call the codesecure_projects << method it does not try to set the id of the codesecure_project_tst_definition table?

I have posted the migrations below

class CreateCodesecureProjects < ActiveRecord::Migration
  def self.up
    create_table :codesecure_projects do |t|
      t.string :name
      t.string :lang

      t.timestamps
    end
  end

  def self.down
    drop_table :codesecure_projects
  end
end


class CreateTstDefinitions < ActiveRecord::Migration
  def self.up
    create_table :tst_definitions do |t|
      t.string :test_name

      t.timestamps
    end
  end

  def self.down
    drop_table :tst_definitions
  end
end


class CreateCodesecureProjectsTstDefinitions < ActiveRecord::Migration
  def self.up
    create_table :codesecure_projects_tst_definitions do |t|
      t.references :codesecure_project
      t.references :tst_definition

      t.timestamps
    end
  end

  def self.down
    drop_table :codesecure_projects_tst_definitions
  end
end

The relevant parts of the models:

class TstDefinition < ActiveRecord::Base
  has_and_belongs_to_many :codesecure_projects
  has_many :tst_datas 

class CodesecureProject < ActiveRecord::Base
  has_many :input_abstractions
  has_and_belongs_to_many :tst_definitions
4

1 回答 1

4

经过一番搜索,我实际上找到了答案,感谢这篇博文http://jimcortez.com/blog/?p=9。我只需要从 codesecure_projects_tst_definitions 表中删除 id 列。所以迁移现在看起来像这样:

class CreateCodesecureProjectsTstDefinitions < ActiveRecord::Migration
  def self.up
    create_table :codesecure_projects_tst_definitions, :id => false do |t|
      t.references :codesecure_project
      t.references :tst_definition

      t.timestamps
    end
  end

  def self.down
    drop_table :codesecure_projects_tst_definitions
  end
end
于 2008-11-03T09:09:02.003 回答