簡體   English   中英

Rails find getting ActiveRecord::RecordNotFound

[英]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?

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

Can't you write

my_record = Record.find(params[:id]) rescue nil
Record.find_by(id: params[:id])

returns Record object if it is found or nil if it is not.

When you call find, you'll obtain an array. When array does not contain objects, count is zero.

items = Store.find(:all, :conditions => {:resource_id => item.id})
if item.count == 0 puts " !not found for item id#{item.id}"

or

if item.nil? puts " !not found for item id#{item.id}"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM