Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord exists? with associations

I have the following ActiveRecord call:

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

Which searches through associations for a payment with id of params[:id]. However, this throws a RecordNotFound exception.

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

I'd like to search only the payments that belong_to that business, and not all payments by doing Payment.exists?(:id => params[:id]). That is so I can know that it's that particular account's business's payment.

How can I do that?

Note: account has_one business and business has_many payments.

like image 953
darksky Avatar asked Jun 20 '13 18:06

darksky


2 Answers

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

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


if @payments.exists?
  # ...
end
like image 56
meagar Avatar answered Oct 21 '22 17:10

meagar


If you only need to check for existence:

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

If you plan on using this record, then call .first instead of exists? since only 1 record is expected. Incidentally, you can also do this using dynamic finders (which are deprecated in Rails 4):

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

This will return nil if no record exists (instead of blowing up).

like image 40
PinnyM Avatar answered Oct 21 '22 18:10

PinnyM