Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails find getting ActiveRecord::RecordNotFound

I have a table that includes a "belongs to" in the model. The table includes the xx_id field to link the two tables.

But, sometimes the xx_id is going to be blank. When it is, I get ActiveRecord::RecordNotFound. I don't want an error - I just want a blank display for this field.

What do you suggest?

like image 450
Reddirt Avatar asked Mar 14 '12 20:03

Reddirt


People also ask

What is ActiveRecord :: Base in Rails?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.

What is the difference between find and Find_by in rails?

The additional difference between find() and find_by() is that find could only be used to search by primary key (usually the 'id') while the find_by() requires and searches by attribute (either passed as hash like Employee. find_by(name: 'Mike') or using the Employee.

What is ActiveRecord in Ruby on Rails?

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.

What are .includes in rails?

Making queries ⚡️ with :includes Rails provides an ActiveRecord method called :includes which loads associated records in advance and limits the number of SQL queries made to the database. This technique is known as "eager loading" and in many cases will improve performance by a significant amount.


2 Answers

Rails will always raise an ActiveRecord::RecordNotFound exception when you use the find method. The find_by_* methods, however, return nil when no record is found.

The ActiveRecord documentation tells us:

RecordNotFound - No record responded to the find method. Either the row with the given ID doesn't exist or the row didn't meet the additional restrictions. Some find calls do not raise this exception to signal nothing was found, please check its documentation for further details.

If you'd like to return nil when records cannot be found, simply handle the exception as follows:

begin   my_record = Record.find params[:id] rescue ActiveRecord::RecordNotFound => e   my_record = nil end 
like image 128
Graham Swan Avatar answered Oct 06 '22 05:10

Graham Swan


Can't you write

my_record = Record.find(params[:id]) rescue nil 
like image 38
dennismonsewicz Avatar answered Oct 06 '22 06:10

dennismonsewicz