Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert primary key value explicitly?

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');
like image 496
prasannaboga Avatar asked May 14 '26 15:05

prasannaboga


1 Answers

Setting ID value is often useful when migrating from legacy data or - as I am doing right now - merging two apps while preserving FK integrity.

I just scratched my head for a while and it seems you have to set the PK value before calling save. After the record is saved, ActiveRecord ignores #id= or update_attribute . So while setting up the record from an attribute hash I use:

article = Article.new(attrs)
article.id = attrs["id"]
article.save!
like image 100
moskyt Avatar answered May 16 '26 05:05

moskyt