简体   繁体   English

如果数据库中不存在 params[:id],我应该如何编写代码

[英]How should I write code if a params[:id] doesn't exist in the db

I'm writing a show action in a controller and want to branch if no id received from params[:id] exists in my database.我正在 controller 中编写一个显示操作,如果我的数据库中不存在从params[:id]接收到的 id,我想分支。

My app is still being created.我的应用程序仍在创建中。 I've tried conditional branching and exception handling.我试过条件分支和异常处理。 However, they didn't work as expected.但是,它们并没有按预期工作。

class ArticlesController < ApplicationController

  #...

  def show
    begin
      @article = Article.find(params[:id])
    rescue
      render root
    end
  end

  #...

end

I expect to be redirect to the root if any error occurs.如果发生任何错误,我希望被重定向到根目录。

The above code returns the record if it is found successfully.上面的代码如果找到成功则返回记录。 However, an ActiveRecord::RecordNotFound in ArticlesController#show occurs if no record is found.但是,如果未找到记录,则会ActiveRecord::RecordNotFound in ArticlesController#show

How should I write code for this error?我应该如何为这个错误编写代码?

How should I write code for this error?我应该如何为这个错误编写代码?

The short answer is "you shouldn't".简短的回答是“你不应该”。

Exceptions should, IMO, be exceptional. IMO,例外应该是例外。 It sounds like you might expect this circumstance, so I suggest you write code that handles the scenario without raising an exception.听起来您可能会预料到这种情况,所以我建议您编写代码来处理这种情况而不会引发异常。

If you really think you'll have circumstances where the Article record does not exist for the given params[:id] (seems a little odd, but I guess it's possible), then I would suggest that you use .find_by instead of .find :如果你真的认为你会遇到给定的params[:id]不存在Article记录的情况(看起来有点奇怪,但我想这是可能的),那么我建议你使用.find_by而不是.find

class ArticlesController < ApplicationController

  #...

  def show
    if @article = Article.find_by(id: params[:id])
      # do something with the article 
    else
      render root
    end
  end

  #...

end

It seems like to you might want to do a redirect instead of a render :在您看来,您可能想要进行redirect而不是render

class ArticlesController < ApplicationController

  #...

  def show
    if @article = Article.find_by(id: params[:id])
      # do something with the article 
    else
      redirect_to root_path
    end
  end

  #...

end

But, maybe not...但是,也许不是...

Also, rescuing everything like this:此外,拯救这样的一切:

def show
  begin
    @article = Article.find(params[:id])
  rescue
    render root
  end
end

...is generally viewed as code smell. ...通常被视为代码气味。 There are a lot of articles on the interwebs about why.网上有很多关于为什么的文章

You can handle the exception from ArticlesController but I advise put the code at ApplicationController like this:您可以处理来自ArticlesController的异常,但我建议将代码放在ApplicationController中,如下所示:

rescue_from ActiveRecord::RecordNotFound do
   redirect_back fallback_location: root_path, alert: t("resource_not_found")
end

Maybe You can code like this:也许你可以这样编码:

 def show
    @article = Article.find_by(id: params[:id])
    unless @article.present?
      flash[:error] = "Not Found."
      redirect_to root_path
    end
  end

why write so much code, while you can achieve with two lines only.为什么要写这么多代码,而你只需要两行就可以实现。

class ArticlesController < ApplicationController
  def show
    @article = Article.find_by(id: params[:id])
    redirect_to root_path unless @article.present?
  end 
end 

Your code should be written like this:你的代码应该这样写:

 def show
    begin
      @article = Article.find(params[:id])
    rescue
      redirect_to root_path
    end
 end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我应该如何处理与请求参数不匹配的模型属性? - How should I handle model attribute that doesn't match request params? 如何验证Project.find(12).present? 如果ID 12不存在,不会报错? - How can I verify Project.find(12).present? and not get an error if ID 12 doesn't exist? 如何验证不与db列对应的参数? - How can I validate params that don't corrospond to a db column? 我更改了列名,现在 heroku db:migrate 不起作用,因为该列不存在 - I changed the column name, now heroku db:migrate doesn't work because the column doesn't exist 如何仅在尚未存在的情况下启用扩展程序? - How do I enable an extension only if it doesn't already exist? RSpec controller 测试无法获取 id 参数。 我不知道如何解决这个问题 - RSpec controller test can't get id params. I don't know how to fix this heroku rake migration db错误关系“ post”不存在 - heroku rake migrate db error relation “post” doesn't exist 如果数据库不存在,则运行rake db:drop而不会失败 - Run rake db:drop without failure if database doesn't exist rake db:migrate语法错误(不存在) - rake db:migrate syntax error (that doesn't exist) 通过参数传递user_id,然后在控制器中检查user_id不起作用 - Passing user_id via params and then checking user_id in controller doesn't work
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM