Looking at the guide it seems like validation errors are handled by the model object's errors attribute so that if a validation fails, the error message goes to that attribute key in the errors hash. However, in my app, the validation failure results in a hard fail as in I see the exception page instead of it going back to the view. Is there something I can set to have it fail "softly"?
Alright try to find reason of failure and then try to put these statements inside ,begin rescue block.
Something like:
begin
# iceberg
rescue
# lifeboat
# maybe add error in the object
# something like: object.errors.add(:email, "Not valid")
end
What do think?
Related
I have an API and I am using ActiveResouce to interact with it.
One of the end point of the API is update.
I am doing user validation errors server side, and returning error response back to the client in case of user validation errors.
But .update_attributes returns boolean value, true/false. I want to use the error response so that I can render it in the UI. How can I do that?
update_attributes just returns a boolean set to true when the save was made correctly.
If you want to check for errors, you can call model.errors and see the messages.
user = User.first
user.update_attributes(username: '') #=> false
user.errors.to_a #=> ["Username can't be blank", "Username must be at least 3 characters"]
You can format and return these errors in your API as you want
Documentation in the source code indicates that an error will raise an exception. You could rescue that exception and return something depending from whatever method you're calling it from. This is just an basic example, but you would want to catch the exception raised, not StandardError, but probably ActiveResource. Since I'm not sure what exception exactly, you can try this and see what the actual exception is, and use that to return something useful in the method.
def some_method(params)
some_api_obj.update_attributes(params)
rescue Exception => e
puts e
end
To assure your records are validated, proceed using .update or .update_attributes as you are doing but you need to set the record first to a variable to get the details of the error if there is.
user = User.first
user.update(name: "Voldemore")
pp user.errors # return array of errors where you can send to UI
Reference for update methods with callbacks and validation:
http://www.davidverhasselt.com/set-attributes-in-activerecord/
I'm wondering what a best practice is for defensively handling ActiveRecord throwing a RecordNotFound exception. It seems that the default Rails behavior is to render a 404 error. That works fine when we're dealing with getting content-- it makes intuitive sense. When I'm doing something like creating an associated record and the parent model's record no longer exists, however, throwing a 404 seems more cryptic.
What if I wanted to, instead, return a validation error complaining that the record no longer exists? How might I go about doing this?
You should really never have a 404 error on your website: you should try to catch all errors and handle them gracefully.
It depends where you're getting the error. If you're in a controller, say, in the edit action, you can just use a rescue, perhaps in conjunction with .exists? so that no error is even actually thrown. Something like this:
def edit
if Model.exists?(params[:id])
#model = Model.find(params[:id])
else
flash[:error] = "Unable to find model with ID #{params[:id]}!"
redirect_to models_path
end
end
You can add a model level validation for this as well. Let's say you have a User which belongs to a Group (i.e, it has a group_id). This validation will ensure that not only a group_id is set, but that it maps to a real Group record.
# User.rb
validates_presence_of: group
That way if you're just throwing params in to a .create! or .save! method, the validation will fail and you'll get a standard Rails error message.
But, your controller should then use the non-exception throwing versions (.create and .save) and again you can do something like above to see if the object is valid, then set a flash if it's not.
Use validates_existence gem
https://github.com/perfectline/validates_existence
I've added the following to my controller's create action:
def create
BatchUser.mass_insert_v2(params[:batch_user][:batch_name], params[:batch_user] [:batch_description], params[:batch_user][:quantity])
redirect_to batch_users_path
end
'mass_insert_v2', in my BatchUser model, starts like this:
def self.mass_insert_v2(batch_name, batch_description, quantity)
#batch_create = BatchUser.create! :batch_name => batch_name, :batch_description => batch_description
...
end
And then goes on to create X user accounts with random usernames and passwords. I've chosen this route because I found raw sql insertion to be faster than using activerecord on its own.
The problem I have is that I'm struggling to render my error messages. For example, batch_name must be present and unique.
I do get an error screen:
ActiveRecord::RecordInvalid in BatchUsersController#create
But no errors show.
Previously, I've had this check in my controller:
respond_to do |format|
if #batch_user.save
....
else
....
But that doesn't seem to work anymore. What can I do to display the errors on the page??
The create! (create with bang!) will throw an exception if the object fails validations. Unless you are planning on catching this exception and handling you might be better off just using create and then checking if the object was created successfully (has an id) and/or has errors.
There are several railsy ways of handling the finding and rendering error messages so you can experiment. However, knowing the following along with the important note above will help get you on track I think:
#batch_user = BatchUser.create(attr_hash) #will give you an object to work with instead of throwing an exception.
If you have an existing object:
#batch_user.valid? #will trigger the validations only and set the object's errors attribute with any relevant data and return a boolean value.
#batch_user.errors #gives you access to the error data (in 3.1 ActiveModel::Errors object)
As far as actually rendering the errors, like I said there are several options. I prefer either putting those error messages (obj.errors.full_messages) in the flash or using something like the dynamic_form plugin.
So I'm parsing data from twitter api in rails using the twitter library, and sometimes the response from api might be like this:
{
error: "Invalid parameter"
}
And the model will raise an exception, right now I'm silently catch it and put the error.message into the log, how do I pass this exception to the controller so I can display it on the view? Thanks.
UPDATE:
The error is likely to happen because I'm allowing my customer to build queries, and they might put advanced queries like "https://search.twitter.com/search.json?since_id=1&&q=near:NYC%20within:15mi" which is supported by the twitter webpage but not by it's API. So I want to catch these kinda of error and display a flash message so the user can have some feedback.
I guess you could an attr_accessor. Something like twitter_errors.
In your model:
attr_accessor :twitter_errors
begin
#your twitter code here
rescue
self.twitter_errors = "whatever"
end
And in your controller, set the flash if #model.twitter_errors isn't empty.
The typical way is to use ActiveModel::Errors.
ActiveRecord uses this mixin extensively for validations. So in an ActiveRecord object you have access to errors.add(:base, TwitterError.to_s). You can use this to set the error when it is caught. And then you should be able to access it via the controller/view using ar_object.errors.
(There are already some helpers for displaying errors like this the docs have much more info)
If a user tries to submit a form or access a service that uses something such as the following underneath the hood:
Model.find(params[:id]) # if model does not exist, throw ActiveRecord::RecordNotFound
If an instance cannot be found, an exception is thrown. Yet I rarely see folks wrap that statement around in a begin/rescue block, even if you create a scaffold, the rails generator does not wrap the find call in begin/rescue blocks.
Is there a reason for that?
I think it's because the most common case is that if you're going after an object by id and it doesn't exist then that is exceptional. The exception will bubble up and rails will handle it as a 404 for you which is usually appropriate.
If it is a situation where the object may or may not exist then either catching the exception or using Model.find_by_id(params[:id]) and checking for a nil object work perfectly well.
One reason may be that error handling logic is passed to rescue handlers in the application.
your controller:
def some_action
#foo = Foo.find!(params[:id])
# Exception will raise here ...
# ...
end
and then specify
rescue_from ActiveRecord::RecordNotFound, :some_method_that_will_render_a_404
(See this for an explanation)
Scaffolds are just shortcuts to get something up-and-running in a short time, but as a rule of thumb scaffolds are not meant to live up to production.
Personally, I've not seen too much code that doesn't do at least basic validation. I'd say it's somewhat a cultural thing: if you don't create a route that would raise an error, you are not obligated to handle it. Obviously this is far from ideal, but I think is not of a priority for many developers. This mainly depends on the business logic: it is usually positively oriented, that is, only contemplates responding to user valid actions.
because it's easier to call:
Model.find_by_id(params[:id])
Which returns nil if no record found
Because you want to fail early. The sooner you find out something's wrong, the sooner you can fix it.
I have seen code like that:
def add_to_cart
begin
product = Product.find(params[:id])
rescue ActiveRecord::RecordNotFound
logger.error("Attempt to access invalid product #{params[:id]}")
redirect_to_index("Invalid product")
else
#cart = find_cart
#cart.add_product(product)
end
end