Ruby-on-rails Rails - 从模型中获取不是验证错误的错误消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1695245/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:56:09  来源:igfitidea点击:

Rails - Getting an error message from the model that is not a Validation error

ruby-on-railserror-handling

提问by raytiley

So I have a method in a reservation model called add_equip. This method does some checking to make sure the added piece of equipment is valid (not conflicting with another reservation).

所以我在一个名为 add_equip 的保留模型中有一个方法。此方法会进行一些检查以确保添加的设备有效(不与其他预留冲突)。

The checks work. If a added piece of equipment shouldn't be added it isn't, and if it should it is.

检查工作。如果不应该添加一件添加的设备,那么它不是,如果应该添加。

The problem is I can't figure out how to send the messages back up to the controller to be put in the flash message? I know I must be missing something here, but I've googled for a few hours now and can't really find any clear explanations how how to pass errors back up the the controller, unless they are validation errors.

问题是我不知道如何将消息发送回控制器以放入 Flash 消息中?我知道我一定在这里遗漏了一些东西,但我已经用谷歌搜索了几个小时,并没有真正找到任何明确的解释如何将错误传递回控制器,除非它们是验证错误。

add_equip in reservations_controller

在reservations_controller 中添加_equip

    def add_equip
    @reservation = Reservation.find(params[:id])
    @addedEquip = Equip.find(params[:equip_id])

    respond_to do |format|
     if @reservation.add_equip(@addedEquip)
        flash[:notice] = "Equipment was added"
        format.html { redirect_to(edit_reservation_path(@reservation)) }
     else
        flash[:notice] = @reservation.errors
        format.html { redirect_to(edit_reservation_path(@reservation)) }
     end
    end
  end

add_equip in reservation model

预留模型中的 add_equip

def add_equip equip
   if self.reserved.find_by_equip_id(equip.id)
     self.errors.add_to_base("Equipment Already Added")
     return false
   elsif !equip.is_available?(self.start, self.end)
     self.errors.add_to_base("Equipment Already Reserved")
     return false
   else
     r = Reserved.new
     r.reservation = self
     r.equip = equip
     r.save
   end
  end

Any help would be greatly appreciated. I know I'm missing something basic here.

任何帮助将不胜感激。我知道我在这里缺少一些基本的东西。

回答by Luke Francl

Using add_to_baseto store the error message seems fine to me, you just need to figure out how to get it into the view.

使用add_to_base来存储错误消息对我来说似乎很好,您只需要弄清楚如何将其放入视图中。

How about:

怎么样:

flash[:notice] = @reservation.errors.full_messages.to_sentence

Assuming you're going to re-display a form, you could also probably use:

假设您要重新显示表单,您也可以使用:

<%= f.error_messages %>

Or possibly:

或者可能:

<%= error_messages_for :reservation %>

Also, you might want to use flash[:error], then you can color it differently with a CSS class in your view.

此外,您可能想要使用 flash[:error],然后您可以在视图中使用 CSS 类为它着色。

回答by Josh K

I think I can see why errors are not being passed back to the user.

我想我能明白为什么错误没有被传回给用户。

The problem is that you are sending a redirect to the user when the action fails instead of just doing a render, that means you lose any variables you set up to use within the request. Instead of adding errors to the flash, just render the edit page and set the flash to a normal message and everything should be fine.

问题在于,当操作失败时,您正在向用户发送重定向,而不是仅执行渲染,这意味着您将丢失在请求中设置使用的任何变量。不要向 flash 添加错误,只需渲染编辑页面并将 flash 设置为正常消息,一切都应该没问题。

For example:

例如:

def add_equip
  @reservation = Reservation.find(params[:id])
  @addedEquip = Equip.find(params[:equip_id])

  respond_to do |format|
    if @reservation.add_equip(@addedEquip)
      flash[:notice] = "Equipment was added"
      format.html { redirect_to(edit_reservation_path(@reservation)) }
    else
      flash[:error] = 'Error adding equipment'
      format.html { render :action => :edit }
    end
  end
end

Now you can continue to use the normal form helpers for displaying error messages.

现在您可以继续使用正常的表单助手来显示错误消息。

Also, just a little suggestion for the model code, try to use i18n when possible (including for flash messages in the controller). Although this is mostly a personal preference, it gives a logical home to all your messages and specific text, and alos allows you to create general or default messages which can be changed in one place instead of duplicating the change in multiple models and controllers.

另外,只是对模型代码的一点建议,尽可能使用 i18n(包括控制器中的 flash 消息)。虽然这主要是个人偏好,但它为您的所有消息和特定文本提供了一个合乎逻辑的位置,并且允许您创建可以在一个地方更改的通用或默认消息,而不是在多个模型和控制器中重复更改。

eg.

例如。

def add_equip equip
  if self.reserved.find_by_equip_id(equip.id)
    self.errors.add_to_base(:already_added)
    return false
  elsif !equip.is_available?(self.start, self.end)
    self.errors.add_to_base(:already_reserved)
    return false
  else
    r = Reserved.new
    r.reservation = self
    r.equip = equip
    r.save
  end
end