gpt4 book ai didi

ruby-on-rails - 在此 Controller /模型设置中如何显示错误?

转载 作者:行者123 更新时间:2023-12-03 09:00:21 25 4
gpt4 key购买 nike

我有一个create方法,该方法在ping某些第三方API的模型中调用一个方法。

我需要做的是,如果API发送回一定的消息,那么我会显示一个错误。

下面是我当前的 Controller 和模型设置,那么如何将错误重新输入到 Controller (最终是 View )中?

这是我的 Controller 中的方法:

def create
@number = Number.where(:tracking => params[:number][:tracking], :user_id => current_user.id).first

if @number.blank?
@number = Number.new
@number.tracking = params[:number][:tracking]
@number.user_id = current_user.id
@number.notes = params[:number][:notes]
@number.track
end

respond_with(@number) do |format|
format.html { redirect_to root_path }
end
end

这是我模型中的方法:
def track
create_events
end


def create_events(&block)

tracker = fedex.track(:tracking_number => number)

if tracker.valid?
self.assign_tracker(tracker)

tracker.events.each do |e|
self.create_event(e) unless (block_given? && !block.call(e))
end

save
else
# NEED TO THROW THE ERROR HERE
end
end

最佳答案

如果只使用验证而不是抛出错误呢?类似于以下内容(只需开始即可。这需要工作。):

# if you don't cache the tracker in an attribute already, do this so
# you can add errors as if it were a column.
attr_accessor :tracker

def create_events(&block)

tracker = fedex.track(:tracking_number => number)

if tracker.valid?
# ...
else
# add the error with i18n
errors.add(:tracker, :error_type_if_you_know_it)

# or add it from a returned message
errors.add(:tracker, nil, :message => fedex.get_error())
end
end

然后在您的 Controller 中:
@number.track

respond_with(@number) do |format|
if @number.errors.any?
format.html { redirect_to root_path }
else
format.html { render :some_template_with_errors }
end
end

也可以使用作为验证的一部分(因此,调用 valid?将按预期工作,并且不会破坏您的自定义“跟踪”错误)
# do your tracking on creation, if number was given
validate :on => :create do
if number.present?
tracker = fedex.track(:tracking_number => number)
unless tracker.valid?
errors.add :tracker, nil, :message => tracker.get_error()
end
end
end

# then do your actual creation of tracking events sometime after validation
before_save :handle_tracker_assignment

def handle_tracker_assignment
self.assign_tracker(tracker)
# note the block method you're using would need to be reworked
# ...
end

请注意,在后一种情况下,您必须稍微更改逻辑,只需传递跟踪编号并尝试保存新记录,这将触发跟踪尝试。

关于ruby-on-rails - 在此 Controller /模型设置中如何显示错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7630747/

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