我正在这样做:
@person.attributes = params[:person]谁能告诉我为什么执行attributes=会导致在我的日志中显示一堆SQL?
我看到几个SELECT,甚至还有一个更新。
我发誓我不是在做“保存”--所以我不知道为什么设置属性会触发查询。
我是否遗漏了after_过滤器的before_?
谢谢。
发布于 2010-03-22 16:25:43
据我所知,在标准模型上设置属性不会导致任何SELECT或UPDATE调用。当我同时运行log和脚本/控制台会话时,这一点进一步体现出来:
>> f = Forum.first
==> ./log/development.log <==
SQL (0.1ms) SET SQL_AUTO_IS_NULL=0
Forum Load (0.4ms) SELECT * FROM `forums` ORDER BY title asc LIMIT 1
Forum Columns (12.6ms) SHOW FIELDS FROM `forums`
=> #<Forum id: 1, title: "Welcome to rBoard!", description: "This is an example forum for Rboard.", is_visible_to_id: nil, topics_created_by_id: nil, position: 1, parent_id: nil, last_post_id: 1, last_post_forum_id: nil, topics_count: 1, posts_count: 4, category_id: nil, active: true, open: true>
>> f.attributes
=> {"position"=>1, "is_visible_to_id"=>nil, "open"=>true, "topics_count"=>1, "title"=>"Welcome to rBoard!", "last_post_forum_id"=>nil, "posts_count"=>4, "id"=>1, "category_id"=>nil, "parent_id"=>nil, "topics_created_by_id"=>nil, "last_post_id"=>1, "description"=>"This is an example forum for Rboard.", "active"=>true}
>> f.attributes = _
=> {"position"=>1, "is_visible_to_id"=>nil, "open"=>true, "topics_count"=>1, "title"=>"Welcome to rBoard!", "last_post_forum_id"=>nil, "posts_count"=>4, "id"=>1, "category_id"=>nil, "parent_id"=>nil, "topics_created_by_id"=>nil, "last_post_id"=>1, "description"=>"This is an example forum for Rboard.", "active"=>true}在这里可以看到,只执行了两个SQL查询,一个用于获取Forum记录,另一个用于查找forums表上的哪些列。
直到我保存它,它才会执行一些查询:
>> f.attributes
=> {"position"=>1, "is_visible_to_id"=>nil, "open"=>true, "topics_count"=>1, "title"=>"Welcome to rBoard!", "last_post_forum_id"=>nil, "posts_count"=>4, "id"=>1, "category_id"=>nil, "parent_id"=>nil, "topics_created_by_id"=>nil, "last_post_id"=>1, "description"=>"This is an example forum for Rboard.", "active"=>true}
>> attr = _
=> {"position"=>1, "is_visible_to_id"=>nil, "open"=>true, "topics_count"=>1, "title"=>"Welcome to rBoard!", "last_post_forum_id"=>nil, "posts_count"=>4, "id"=>1, "category_id"=>nil, "parent_id"=>nil, "topics_created_by_id"=>nil, "last_post_id"=>1, "description"=>"This is an example forum for Rboard.", "active"=>true}
>> attr["position"] = 2
=> 2
>> f.save
SQL (0.2ms) BEGIN
=> true
>> SQL (0.2ms) COMMIT
f.attributes = attr
=> {"position"=>2, "is_visible_to_id"=>nil, "open"=>true, "topics_count"=>1, "title"=>"Welcome to rBoard!", "last_post_forum_id"=>nil, "posts_count"=>4, "id"=>1, "category_id"=>nil, "parent_id"=>nil, "topics_created_by_id"=>nil, "last_post_id"=>1, "description"=>"This is an example forum for Rboard.", "active"=>true}
>> WARNING: Can't mass-assign these protected attributes: id
f.save
SQL (0.2ms) BEGIN
Forum Update (20.3ms) UPDATE `forums` SET `position` = 2 WHERE `id` = 1
SQL (27.2ms) COMMIT
=> truehttps://stackoverflow.com/questions/2490624
复制相似问题