如果方程无法运行,则将变量分配为方程的输出或 nil(规避 NoMethodError)

Assign variable as either output of equation OR nil if equation can't run (circumventing NoMethodError)

我正在保存一个对象:

@rentalrequest = RentalRequest.new do |rr|
  rr.delivery_start = Time.zone.parse(request_params[:deliverydate] + " " + request_params[:deliverytime_start]).utc
  ...
end

每隔一段时间,我的前端验证就会失败,不知何故,即使 deliverydatedeliverytime_start 为空白,表单也会发布。在这种情况下,控制器会以 NoMethodError 中断,因为此语句没有意义: Time.zone.parse("")

但是,我觉得如果我能直接说 rr.delivery_start = nil if Time.zone.parse doesn't work 就可以轻松得多,而不是在发生这种情况时写一个救援。这样,@rentalrequest 对象的后端验证就会启动并起到救援作用。

但我不确定如何编写 rr.delivery_start = nil if Time.zone.parse doesn't work(比如...如果它的任何部分不起作用)

想法?

如何检查这些参数是否存在?

@rentalrequest = RentalRequest.new do |rr|
  rr.delivery_start = nil
  if request_params[:deliverydate].present? && request_params[:deliverytime_start].present?
    rr.delivery_start = Time.zone.parse(request_params[:deliverydate] + " " + request_params[:deliverytime_start]).utc
  end
  ...
end

你的计算错了地方,你的模型应该会自己保持自己的状态。可能是这样的:

class RentalRequest < ActiveRecord::Base
  before_validation :set_delivery_start
private
  def set_delivery_start
    # Presumably validations will catch these conditions...
    return if(!deliverydate || !deliverytime_start)
    self.delivery_start = ... # whatever calculation matches the deliverydate and delivertime_start types goes here
  end
end

然后您将进行验证以确保所有三个交付值都有意义。

如果 new 块在控制器中,您可以 require 这些参数。

def request_params
  params
    .require(:rental_request)
    .permit(..., :deliverydate, :deliverytime_start)
    .require(:deliverydate, :deliverytime_start)
end