views:

27

answers:

1

I have a table called messages and here is the table structure, I don’t want id is auto increment field but it should be a primary key for that table.

Here is table structure for messages

CREATE TABLE `messages` (
      `id` INT(11) NOT NULL,
      `user_id` INT(11) NOT NULL,
      `text` VARCHAR(255) NOT NULL,
      `source` VARCHAR(100),
      `created_at` DATETIME DEFAULT NULL,
      `updated_at` DATETIME DEFAULT NULL,
      PRIMARY KEY (`id`)
    );

while insert the data into table I am using below hash object

msg['id'] = 12345; 
msg['user_id'] = 1;
msg['text'] = 'Hello world';

If I save this hash into messages table, id is not inserting

message = Message.new(msg);
message.save!

Rails is building insert sql with out id, so id value is not inserting messages table.

How insert the id value in table, This the insert sql rails build with out using id field

INSERT INTO `users` (`updated_at`, `user_id `, `text`, `created_at`) VALUES('2010-06-18 12:01:05', '1', 'Hello world', '2010-06-18 12:01:05');
+4  A: 

You're working against the way rails works. ActiveRecord reserves the use of the id column and manages it for you.

  • Why should id not be an auto-incrementing column if it's the primary key?
  • Why do you need to control its value?

If you need an id column you can control yourself, add another one. It won't be the primary key, but you can make it a unique index too.

Andrew Vit