在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
首先,我认为id
未设置为MySQL数据库中的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 | |
+------------------+--------------+------+-----+---------+----------------+
任何人都知道这会怎样?提前谢谢。
修改:
请注意c.save
的SQL解释是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)
好吧,这条记录实际上是插入数据库的。
comments
更多测试:
commentable_id