我有以下 ActiveRecord 调用:
@payment = account.business.payments.find(params[:id])
它通过关联搜索 ID 为 params[:id]
的 payment
。但是,这会引发 RecordNotFound 异常。
我想调用 exists?
来查看记录是否存在以避免抛出异常。执行 Payment.exists?(account.business.payments.find(params[:id]))
不起作用。
我只想搜索属于
的业务
的付款
,而不是通过执行Payment.exists来搜索所有付款?(:id => 参数[:id])
。这样我就可以知道这是该特定帐户的业务付款。
我该怎么做?
注意:
account
has_one business
和 business
has_many payments
.
最佳答案
使用 where
而不是 find
,它将返回一个 ActiveRecord::Relation
表示 0 条或多条记录,您可以从中链接.exists?
:
@payments = account.business.payments.where(id: params[:id])
if @payments.exists?
# ...
end
关于ruby-on-rails - ActiveRecord 存在吗?与协会,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17221265/