gpt4 book ai didi

ruby-on-rails - destroy 方法似乎不起作用

转载 作者:行者123 更新时间:2023-12-04 06:03:47 26 4
gpt4 key购买 nike

我正在使用 ruby​​ 1.8.7 和 Rails 3.0.3 阅读 PragProg 的 Agile Rails 开发手册

我的 ProductsController 上的这个销毁方法不会删除我的产品,我不明白为什么。

这是我的第一个剪辑,我希望“能正常工作”

  def destroy
@product = Product.find(params[:id])
@product.destroy
respond_to do |format|
format.html { redirect_to(products_url) }
format.xml { head :ok }
end
end

但是我断言 Product.count 的测试失败了。

如果我更改为使用这样的删除类方法:

  def destroy
Product.delete(params[:id])
respond_to do |format|
format.html { redirect_to(products_url) }
format.xml { head :ok }
end
end

我的测试通过了。

这是测试

  test "should destroy product" do
assert_difference('Product.count', -1) do
if @product.referenced_by_line_item
@product.line_items.remove_all
end
delete :destroy, :id => @product.to_param
end

assert_redirected_to products_path
end

我的产品模型类有一个 before_destroy 方法

  def referenced_by_line_item
if line_items.count.zero?
return true
else
errors.add(:base, 'Line Items present')
return false
end
end

你知道我在这里做错了什么吗?通过阅读文档(并在此处搜索其他问题),我希望 @product.destroy 和 Product.delete(id) 做同样的事情。

谢谢!

最佳答案

您在执行任何操作之前都会调用referenced_by_line_item。如果存在订单项,则返回 false,因此您不会删除订单项。我认为这不是您想要的行为。如果您将其更改为:

  if <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="50711020223f342533247e2235363522353e333534" rel="noreferrer noopener nofollow">[email protected]</a>_by_line_item
@product.line_items.remove_all
end
delete :destroy, :id => @product.to_param

那么@product.destroy可能会起作用。

尽管颠倒 referenced_by_line_item 中的逻辑可能更有意义。更有意义的说法是,如果存在与该产品关联的订单项,则该产品由订单项引用。我认为你的逻辑是倒退的。

此外, bool 方法应以“?”结尾

不过我看到了这里的复杂性。你希望它在有行项的时候返回false,这样就不保存,但是返回值与方法名不一致。也许这样的东西会更好:

def no_line_items_present?
if line_items.count > 0
# add errors
return false
else
return true
end
end

然后你可以说:

  @product.line_items.remove_all unless @product.no_line_items_present?
delete :destroy, :id => @product.to_param

尽管我不认为在决定删除订单项之前检查订单项有什么意义,除非性能略有提高。

关于ruby-on-rails - destroy 方法似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4461956/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com