find_by_sql in Rails, accessing the resulting array

后端 未结 5 1961
日久生厌
日久生厌 2020-12-30 17:09

I\'m trying to run a query in a very quick and dirty way in Rails, without putting the rest of the model in place. I know this is bad practice but I just need a quick resul

5条回答
  •  死守一世寂寞
    2020-12-30 18:01

    Since you are defining an instance method, I think it should return the price if it exists or nil

    Try something like this:

    def shipping_price
      ShippingZonePrice.find_by_sql(
        "SELECT z.price as price
         FROM shipping_zone_prices z, items i
         WHERE i.id = '#{self.id}'
         AND z.weight_g > d.weight
         ORDER BY z.weight_g asc limit 1").first.try(:price)
    end
    

    Then this should work for you:

    @item.shipping_price
    

    The first.try(:price) part is needed because find_by_sql may return an empty array. If you tried to do something like first.price on an empty array, you would get an exception along the lines of NoMethodError: undefined method 'price' for nil:NilClass.

提交回复
热议问题