我有以下型号:
供应商有许多提交的价格
Submitted_prices 有很多 price_items
为了使代码在没有提交价格和/或价格项目时不会崩溃,我曾经使用以下内容:
if supplier.submitted_prices.where(:purchaser_id => organization.id).last
&& supplier.submitted_prices.where(:purchaser_id => organization.id).last.price_items.where("item_id" => item.id).last
&& supplier.submitted_prices.where(:purchaser_id => organization.id).last.price_items.where("item_id" => item.id).last.unit_price.present?
order_item.unit_price = supplier.submitted_prices.where(:purchaser_id => organization.id).last.price_items.where("item_id" => item.id).last.unit_price
然后我遇到了try():
order_item.unit_price = supplier.try(:submitted_prices).where(:purchaser_id => organization.id).try(:last).try(:price_items).where("item_id" => item.id).try(:last).try(:unit_price)
问题是,我不知道如何在 WHERE 约束上运行 try(),如果 try 返回 nil,此约束将失败:
NoMethodError Exception: undefined method `where' for nil:NilClass
有没有办法将 try() 包裹在 WHERE 约束周围?