Nil vs RecordNotFound for a failed query - sql

When I do
User.find_by_username('some_user')
and it fails to find the user the above query returns nil. However,
User.find(1)
throws an ActiveRecord::RecordNotFound error if it fails to find the user. The rails guide says this is supposed to happen but doesn't explain why. That's my question, why are there two different behaviors? Thanks!

ActiveRecord::RecordNotFound is raised only when record with given id(s) is not found.
If you don't want the exception when searching by id, you can use:
User.find_by_id('foo')
The difference to me is:
User.find: get me that user.
User.find_by_foo('foo'): is there a user with foo == foo?
The first (1) assumes existence of your record so failure should raise an exception.
The second (2) assumes you want to query the existence of your record so missing record results to nil.

Related

apex addError - remove default error message

I have added addError to my record like in the following.
v.addError('My Error message');
But I get the error message like in the following.
I don't want the default part "Error: Invalid Data. Review all error messages to correct your data".
I tried adding to some field instead of adding it to the whole record.
But in this case, it implies that the error is specific to what the user has entered in that field. But this is not what I want. My error is record specific.
In a nutshell, based on some condition, I want to stop a record being inserted. This is actually to be added to before insert of my trigger.
Please help.
Try this Code for field level error message:
trigger AccountTrigger on Account (before insert) {
for(Account accIns :trigger.new){
if(accIns.Rating == 'Hot'){
accIns.Rating.addError('My Error message');
}
}
}

ActiveRecord::StatementInvalid·Mysql2::Error: Deadlock found when trying to get lock; try restarting transaction:

So I have this after_save method that runs to ensure that this current address object is the only address that is active under that user.
before_save ensure_one_active_address
def ensure_one_active_address
Address.where("active = ? AND user_id = ? AND id NOT IN (?)", active, user_id, id).update_all(active: 0) if active
end
Unfortunately, I'm getting the following error:
ActiveRecord::StatementInvalid·Mysql2::Error: Deadlock found when trying to get lock; try restarting transaction
I can't reproduce the error, only happens in production. I understand what the error means, but I don't understand where it's happening. Is the update_all happening before the where query can finish?
If you really want to use this callback, you should use after_commit instead of after_save.

robot framework: exception handling

Is it possible to handle exceptions from the test case? I have 2 kinds of failure I want to track: a test failed to run, and a test ran but received the wrong output. If I need to raise an exception to fail my test, how can I distinguish between the two failure types? So say I have the following:
*** Test Cases ***
Case 1
Login 1.2.3.4 user pass
Check Log For this log line
If I can't log in, then the Login Keyword would raise an ExecutionError. If the log file doesn't exist, I would also get an ExecutionError. But if the log file does exist and the line isn't in the log, I should get an OutputError.
I may want to immediately fail the test on an ExecutionError, since it means my test did not run and there is some issue that needs to be fixed in the environment or with the test case. But on an OutputError, I may want to continue the test. It may only refer to a single piece of output and the test may be valuable to continue to check the rest of the output.
How can this be done?
Robot has several keywords for dealing with errors, such as Run keyword and ignore error which can be used to run another keyword that might fail. From the documentation:
This keyword returns two values, so that the first is either string
PASS or FAIL, depending on the status of the executed keyword. The
second value is either the return value of the keyword or the received
error message. See Run Keyword And Return Status If you are only
interested in the execution status.
That being said, it might be easier to write a python-based keyword which calls your Login keyword, since it will be easier to deal with multiple exceptions.
You can use something like this
${err_msg}= Run Keyword And Expect Error * <Your keyword>
Should Not Be Empty ${err_msg}
There are couple of different variations you could try like
Run Keyword And Continue On Failure, Run Keyword And Expect Error, Run Keyword And Ignore Error for the first statement above.
Option for the second statement above are Should Be Equal As Strings, Should Contain, Should Match.
You can explore more on Robot keywords

Transactions in Datamapper & Rails (dm-rails)

I have two models: hotel and location. A location belongs to a hotel, a hotel has one location. I'm trying to create both in a single form, bear in mind that I can't use dm-nested for nested forms due to a dependency clash.
I have code that looks like:
if (#hotel.save && #location.save)
# process
else
# back to form with errors
end
Unfortunately, #hotel.save can fail and #location.save can complete (which confuses me because I didn't think the second condition would run in an AND block if the first one failed).
I'd like to wrap these in a transaction so I can rollback the Location save. I can't seem to find a way to do it online. I'm using dm-rails, rails 3 and a postgresql database. Thanks.
The usual way to wrap database operations in DataMapper is to do something like this:
#hotel.transaction do
#hotel.save
#location.save
end
Notice that #hotel is quite arbitrary there; it could as well be #location or even a model name like Hotel.
In my experience, this works best when you enable exceptions to be thrown. Then if #hotel.save fails, it will throw an exception, which will be caught by the transaction block, causing the transaction to be rolled back. The exception is, of course, reraised.

Rails 3 - how to make own error handler

could anyone help me, please, how to make my own error handler for example for the situation, when I am trying to destroy the item from database, that doesn't exist (delete item with don't exist ID)?
I tried to search on google, but I still haven't something, what works.
I guess you will never read this, but it can help others. You have a problem with .find cause it raise an exception when your id is wrong.
You have 3 ways to manage it.
You can catch the exception with a rescue. But that's not the best way.
You can check if your id exists, you have few ways to do this way. (count for example). But that's not the best way, cause you have 2 queries.
Or you can use find_by_id. This does not raise an exception, and return nil when your object does not exist. You only have to check about the result.
your_item = YourModel.find_by_id(non_existent_id) # returns nil
# PS: YourModel.find(non_existent_id) would raise exception
if your_item
your_item.destroy
flash[:notice] = "Deleted item with id #{non_existent_id}"
else
flash[:error] = "Cannot find item with id #{non_existent_id}"
end