How to insert a primary key value explicitly?

I have a table called messages, and here is the structure of the table, I do not want the identifier to be an automatically additional field, but it should be the primary key for this table.

Here is the 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`)
    );

inserting data into a table i use below hash object

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

If I save this hash in the message table, the id does not insert

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

Rails builds an sql insert without an identifier, so the id value does not insert a message table.

How to insert id value in table.This inserts build sql rails without 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');
+3
source share
2 answers

ID - - FK.

, , , PK , . ActiveRecord # id = update_attribute. :

article = Article.new(attrs)
article.id = attrs["id"]
article.save!
+4

, . ActiveRecord id .

  • id , ?
  • ?

, , . , .

-1

Source: https://habr.com/ru/post/1751333/


All Articles