I have a create method that calls a method in a model that pings some third-party APIs.
What I need to do is if the API sends back a certain message, then I’d display an error.
Below is my current controller and model setup, so how would I get the error back in to the controller (and ultimately the view)?
Here is the method in my 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
Here are the methods in my model:
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
How about if rather than throwing errors, you just use validation? Something like the following (Just to get your started. This would need work.):
Then in your controller:
Alternatively you could do this as part of validation (so calling
valid?would work as expected and not destroy your custom “track” errors)Note in the latter case you’d have to change your logic a bit, and simply pass the tracking number and attempt to save a new record, which would trigger the tracking attempt.