简体   繁体   English

Rails:调用 Model.new 时 id 字段为零

[英]Rails: id field is nil when calling Model.new

I am a little confused about the auto-increment id field in rails.我对 rails 中的自动增量 id 字段有点困惑。 I have a rails project with a simple schema.我有一个带有简单模式的 rails 项目。 When i check the development.sqlite3 I can see that all of my tables have an id field with auto increment.当我检查 development.sqlite3 时,我可以看到我所有的表都有一个自动递增的 id 字段。

CREATE TABLE "messages" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "text" text, "created_at" datetime, "updated_at" datetime);

But when I call Message.new in the console, the resulting object has an id of nil .但是当我在控制台中调用Message.new时,结果对象的idnil

>> a = Message.new
=> #<Message id: nil, text: nil, created_at: nil, updated_at: nil>

Shouldn't the id come back populated? id不应该回来填充吗?

No, that's the correct behavior.不,这是正确的行为。 When you create an object via new (as in your example), Rails doesn't persist it to the database (just in memory).当您通过new创建对象时(如您的示例中所示),Rails 不会将其持久化到数据库中(仅在内存中)。

If you do Message.create , or Message.save like theIV said, then the id will be populated.如果您像theIV所说的那样执行Message.createMessage.save ,则将填充id

Like fig said,就像无花果说的,

n = Movie.new
n.save
=> true

means that it is saved and will be given an ID.意味着它被保存并被赋予一个 ID。 Alternatively,或者,

n = Movie.create!

automatically saves and stores it in the database and gives it an ID with one line of code.自动保存并存储在数据库中,并用一行代码给它一个ID。

据我所知, id字段只在save s上分配,而不是在new s上分配。

All answers above are correct.以上所有答案都是正确的。 To add to them, calling the #save method on an instance will return true if it was able to insert into database and false if it wasn't successful.要添加到它们,如果能够插入到数据库中,则调用实例上的#save方法将返回true如果它不成功,则返回false Using the ::create method will make a new instance of your model, and will call #save on it.使用::create方法将为您的模型::create一个新实例,并对其调用#save

You can also use the #save!您也可以使用#save! or ::create!::create! methods.方法。 The difference is that these will raise an error (as opposed to returning boolean) if they were not successful in their insertion to the database.不同之处在于,如果它们没有成功插入到数据库中,则会引发错误(与返回布尔值相反)。

In my case, I called Model.create(event_id) with constant value (6) that was NOT the event's actual id.就我而言,我使用常量值 (6) 调用 Model.create(event_id),这不是事件的实际 id。 There was no error, and an Active Record Model was returned with other attributes, except id was nil.没有错误,返回一个带有其他属性的 Active Record Model,除了 id 为零。

I fixed my bug after some hours of debugging by changing the value to the actual reference id of the existing Event.id (as it was previously).经过几个小时的调试后,我通过将值更改为现有 Event.id 的实际引用 ID(就像以前一样)修复了我的错误。 Note that you might get this error if you have SQL foreign constraint to some other table, but you are using incorrect id for the reference.请注意,如果您对某个其他表具有 SQL 外部约束,但您使用的引用 ID 不正确,您可能会收到此错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM