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
.
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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With