Rails try()方法与活动查询中的约束

mig*_*igu 0 ruby ruby-on-rails

我有以下型号:

供应商有很多提交的商品

Submitted_prices有很多price_items

为了在没有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 
Run Code Online (Sandbox Code Playgroud)

然后我遇到了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)
Run Code Online (Sandbox Code Playgroud)

问题是,我不知道如何在WHERE约束上运行try(),如果try返回nil,则此约束会失败:

NoMethodError Exception: undefined method `where' for nil:NilClass
Run Code Online (Sandbox Code Playgroud)

有没有办法围绕WHERE约束包装try()?

Ser*_*abe 6

首先,不要使用try,恕我直言,这是一个代码气味.

如果您仍然想要,那么您需要在第一次尝试后的每次通话中使用它.

supplier.try(:submitted_prices).try(:where, {purchaser_id: organization.id}).try(:last).try(:price_items).try(:where, {item_id: item.id}).try(:last).try(:unit_price)
Run Code Online (Sandbox Code Playgroud)

这肯定显示出一些糟糕的设计.尝试先重构它!