【问题标题】:Activerecode HABTM primary key problemActiverecode HABTM 主键问题
【发布时间】:2008-11-03 08:28:08
【问题描述】:

我必须使用具有多对多关系的表。我已经创建了正确的表 codesecure_project_tst_definition 并且它可以工作。我可以通过在 TstDefinition 对象上调用 codesecure_projects

我已经在下面发布了迁移

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

模型的相关部分:

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

【问题讨论】:

  • 你能告诉我们包含关联行的类定义吗?
  • 我无法理解这个问题.. 发布表格架构.. 就像 Gareth 说的那样.. 发布 AR 模型类可能会有所帮助

标签: ruby-on-rails activerecord associations


【解决方案1】:

经过一番搜索,我实际上找到了答案,感谢这篇博文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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-30
  • 1970-01-01
  • 1970-01-01
  • 2012-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多