ActiveRecord: manually setting :id

Hey everyone,

I’m having a problem with ActiveRecord (outside of Rails) where it
doesn’t allow me to set the value of the :id column. Since you’re
probably not normally supposed to fiddle with the primary key, I’m
guessing that this isn’t a bug, but is intentional. Is there any way
to override it?

The reason I need this is that I’m making a library that loads data
from a relational-like XML format into various other
databases/formats. Since the primary keys were already established in
the application that made the XML file, I need to be able to link the
records using those ids, and not the auto-increment values that MySQL
(or any other DB) assigns.

I’d rather not use raw SQL to do this so that I can get this to work
with all of the DBs that AR supports out of the box. Any ideas?

Thanks,
Andrew

Hi,

Maybe this document will helps you;
http://ar.rubyonrails.com/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html

Especially these parts;

Rename the primary key column

create_table(:objects, :primary_key => ‘guid’) do |t|
t.column :name, :string, :limit => 80
end

generates:

CREATE TABLE objects (
guid int(11) DEFAULT NULL auto_increment PRIMARY KEY,
name varchar(80)
)

But i never use active record out side of rail. But also i think that
the concept will be same. You can find more detailed infi in the source
code of active record. it has a well documanted.

Andrew O’Brien wrote:

Hey everyone,

I’m having a problem with ActiveRecord (outside of Rails) where it
doesn’t allow me to set the value of the :id column. Since you’re
probably not normally supposed to fiddle with the primary key, I’m
guessing that this isn’t a bug, but is intentional. Is there any way
to override it?

The reason I need this is that I’m making a library that loads data
from a relational-like XML format into various other
databases/formats. Since the primary keys were already established in
the application that made the XML file, I need to be able to link the
records using those ids, and not the auto-increment values that MySQL
(or any other DB) assigns.

I’d rather not use raw SQL to do this so that I can get this to work
with all of the DBs that AR supports out of the box. Any ideas?

Thanks,
Andrew

And if u ask override it when you are using Active record in classes
this will be helpful;

class Child < ActiveRecord::Base
belongs_to :parents , :primary_key => “name”
end

Andrew O’Brien wrote:

I’m having a problem with ActiveRecord (outside of Rails) where it
doesn’t allow me to set the value of the :id column. Since you’re
probably not normally supposed to fiddle with the primary key, I’m
guessing that this isn’t a bug, but is intentional. Is there any way
to override it?

Yes, if you mean that “Model.new(:id => ‘foo’).save” doesn’t work. Try
“Model.new { |m| m.id = 42 }”, that seems to work for me.

– Steve