class Child < ApplicationRecord
belongs_to :parent
end
class Parent < ApplicationRecord
has_many :children
end
irb(main):073:0> child = Child.last
Child Load (0.4ms) SELECT "children".* FROM "children" ORDER BY "children"."id" DESC LIMIT $1 [["LIMIT", 1]]
+----+----------------------+-----------+---------------------------+---------------------------+
| id | title | parent_id | created_at | updated_at |
+----+----------------------+-----------+---------------------------+---------------------------+
| 1 | this is childs title | 1 | 2018-08-23 12:09:37 +0900 | 2018-08-23 12:09:37 +0900 |
+----+----------------------+-----------+---------------------------+---------------------------+
1 row in set
irb(main):074:0> child.save
(0.4ms) BEGIN
Parent Load (0.5ms) SELECT "parents".* FROM "parents" WHERE "parents"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
(0.4ms) COMMIT
=> true
代码是这样的。 当我保存孩子时,将发生父选择查询。 我不知道为什么会发生这种情况,有可能避免这种情况吗?
在我的情况下,父级有许多列且很大,因此自动加载它会占用大量内存。
答案 0 :(得分:0)
通过这种方式,您可以避免在保存孩子之前先致电给父母
Child.new(title: 'this is childs title', parent_id: parent.id)