Thursday, February 17, 2011

Activerecode HABTM primary key problem

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
From stackoverflow
  • After some searching I actually found the answer, thanks to this blog post http://jimcortez.com/blog/?p=9. I simply needed to remove the id column from the codesecure_projects_tst_definitions table. So the migration now looks like this:

    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
    
    Gareth : I was just typing this up lol. You should also consider using a `has_many :through` association which makes the join table into a real join model. This was added 2 years ago [http://weblog.rubyonrails.org/2006/04/21/habtm-vs-has_many-through/] but there's probably some more indepth references around

0 comments:

Post a Comment