id
ActiveRecord 的 仍然nil
在 之后真的很尴尬save
。
我在控制台中的命令如下:
irb(main):003:0> c = Comment.new
=> #<Comment id: nil, commentable_id: nil, commentable_type: nil, user_id: nil, content: "", del_flg: 0, created_at: nil>
irb(main):004:0> c.commentable = Moment.last
Moment Load (0.2ms) SELECT `moments`.* FROM `moments` ORDER BY `moments`.`id` DESC LIMIT 1
=> #<Moment id: 119583...
irb(main):005:0> c.user = User.find(119)
User Load (0.2ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 119 LIMIT 1
=> #<User id: 119...
irb(main):006:0> c.save
(0.2ms) BEGIN
SQL (0.6ms) INSERT INTO `comments` (`commentable_id`, `commentable_type`, `content`, `created_at`, `del_flg`, `id`, `user_id`) VALUES (119583, 'Moment', '', '2013-01-22 15:19:05', 0, NULL, 119)
(0.1ms) COMMIT
=> true
irb(main):007:0> c
=> #<Comment id: nil, commentable_id: 119583, commentable_type: "Moment", user_id: 119, content: "", del_flg: 0, created_at: "2013-01-22 15:19:05">
irb(main):008:0> c.id
=> nil
这就是我定义我的记录的方式:
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :commentable, polymorphic: true
end
起初,我以为是我的 MySQL 数据库id
中没有设置PRIMARY KEY
,所以我检查了它:
mysql> describe comments;
+------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| commentable_id | int(11) | NO | MUL | NULL | |
| commentable_type | varchar(100) | NO | MUL | NULL | |
| user_id | int(11) | NO | | NULL | |
| content | text | NO | | NULL | |
| del_flg | tinyint(4) | NO | | 0 | |
| created_at | datetime | NO | | NULL | |
+------------------+--------------+------+-----+---------+----------------+
任何人都知道这将如何发生?提前致谢。
编辑:
只需意识到 SQL 的解释c.save
是INSERT INTO
comments
(commentable_id
, commentable_type
, content
, created_at
, del_flg
, id
, user_id
) VALUES (119583, 'Moment', '', '2013-01-22 15:19:05', 0, NULL, 119)
好吧,这条记录实际上是插入到数据库中的。
mysql> select * from comments where commentable_id = 119583 and commentable_type = "Moment"
-> ;
+-------+----------------+------------------+---------+---------+---------+--------- ------------+
| id | commentable_id | commentable_type | user_id | content | del_flg | created_at |
+-------+----------------+------------------+---------+---------+---------+---------------------+
| 26582 | 119583 | Moment | 119 | | 0 | 2013-01-22 14:58:22 |
| 26583 | 119583 | Moment | 119 | | 0 | 2013-01-22 15:09:11 |
| 26585 | 119583 | Moment | 119 | | 0 | 2013-01-22 15:19:05 |
| 26586 | 119583 | Moment | 119 | | 0 | 2013-01-22 15:38:14 |
+-------+----------------+------------------+---------+---------+---------+---------------------+
更多测试:
irb(main):009:0> c.persisted?
=> true
irb(main):010:0> c.errors
=> #<ActiveModel::Errors:0x00000004761958 @base=#<Comment id: nil, commentable_id: 119583, commentable_type: "Moment", user_id: 119, content: "", del_flg: 0, created_at: "2013-01-22 16:52:59">, @messages={}>