3

在 Rails 控制台中,我这样做:

input = Input.create :name => "foo"
=> #<Input id: 8, name: "foo", created_at: "2013-05-07 11:45:17", updated_at: "2013-05-07 11:45:17">
Input.all
=> [#<Input id: 8, name: "foo", created_at: "2013-05-07 11:45:17", updated_at: "2013-05-07 11:45:17">]
input
=> #<Input id: 8, name: "foo", created_at: "2013-05-07 11:45:17", updated_at: "2013-05-07 11:45:17">
input.destroy
=> #<Input id: 8, name: "foo", created_at: "2013-05-07 11:45:17", updated_at: "2013-05-07 11:45:17">
> Input.all
=> []
> input
=> #<Input id: 8, name: "foo", created_at: "2013-05-07 11:45:17", updated_at: "2013-05-07 11:45:17">
> input.reload
ActiveRecord::RecordNotFound: Couldn't find Input with id=8
> input
=> #<Input id: 8, name: "foo", created_at: "2013-05-07 11:45:17", updated_at: "2013-05-07 11:45:17">

我真正希望看到的是:

> input
=> nil

该对象已从数据库中删除,但变量仍然存在并且仍在尝试指向它。这是怎么回事?

4

2 回答 2

3

input变量在内存中存储对实例的引用。销毁记录将从数据库中删除该行。调用input.reload( docs ) 会在尝试查找记录时引发异常,但不会nil代表您将变量的值设置为。

此行为在您希望在其中显示有关已删除对象的信息的 DELETE 请求范围内很有用。例如:

class WidgetsController < ApplicationController
  def destroy
    @widget = Widget.find(params[:id])
    @widget.destroy
    respond_with @widget, notice: "You successfully removed #{@widget.name}"
  end
end  
于 2013-05-07T11:59:43.253 回答
1

destroy 方法对数据库进行 SQL 调用并销毁包含它的表中的行。它仍然允许您在应用程序中操作对象,只要它仍在范围内(即)即使在销毁对象之后也允许回调和过滤器。

如果我们不想触发回调或者想要更好的性能,最好使用“delete”

您可以使用input.delete

于 2013-05-07T11:59:09.263 回答