Rails 操作中的救援使用,无需开始

问题描述 投票:0回答:1

如果没有 begin 关键字,这是如何工作的?

def show
  @post = BlogPost.find(params[:id])
rescue ActiveRecord::RecordNotFound
  redirect_to root_path
end

为什么不是?

def show
  begin
    @post = BlogPost.find(params[:id])
  rescue ActiveRecord::RecordNotFound
    redirect_to root_path
  end
end

两种变体都有效。我试过了。但我很难理解第一个。

ruby-on-rails ruby
1个回答
0
投票

begin/end
只是可以使用
rescue
的地方之一。只需将
begin
替换为
def
do
,其概念上是相同的:

begin
  err
rescue
  "error"
end

def m
  err
rescue
  "error"
end

[1].map do |i|
  err
rescue
  "error"
end

class
module
也可以使用,不确定你会用它做什么:

class A
  err
rescue
  "error"
end

module B
  err
rescue
  "error"
end

https://docs.ruby-lang.org/en/3.3/syntax/exceptions_rdoc.html

© www.soinside.com 2019 - 2024. All rights reserved.