Does ActiveRecord exist? with associations

I have the following ActiveRecord call:

@payment = account.business.payments.find(params[:id]) 

What is looking through associations for payment with the identifier params[:id] . However, this raises a RecordNotFound exception.

I would like to call exists? to see if a record exists to avoid an exception. Doing Payment.exists?(account.business.payments.find(params[:id])) does not work.

I would like to look only for payments , what belong_to , that business , and not all payments by doing Payment.exists?(:id => params[:id]) . This means that I know that this is a specific business payment.

How can i do this?

Note: account has_one business and business has_many payments .

+7
source share
3 answers

Use where instead of find , it will return ActiveRecord::Relation representing 0 or more records from which you can link .exists? :

 @payments = account.business.payments.where(id: params[:id]) if @payments.exists? # ... end 
+12
source

If you only need to check availability:

 account.business.payments.where(:id => params[:id]).exists? 

If you plan to use this entry, call .first instead of exists? since only 1 entry is expected. By the way, you can also do this with dynamic crawlers (which are deprecated in Rails 4):

 account.business.payments.find_by_id(params[:id]) 

This will return nil if the record does not exist (instead of exploding).

+3
source

Someone may cancel if I am wrong, but I would suggest

 account.business.payments.where(:id => params[:id]).pluck(:id).present? 

By performing a break, you skip an instance of related objects. This means that they do not need to be loaded into memory, which will save several cycles if you do this a lot.

0
source

All Articles