我试图在 Rails 中以非常快速和肮脏的方式运行查询,而不将模型的其余部分放在适当的位置。我知道这是不好的做法,但我只需要在紧迫的时间内快速得到结果,直到我找到整个解决方案。
我的商品有基于重量的运费。重量存储在商品中,价格存储在表shipping_zone_prices中,我当前所做的就是查找与第一行相关的价格,其中重量比待售商品重:
class Item < ActiveRecord::Base
def shipping_price
item_id = self.id
shipping_price = ShippingZonePrice.find_by_sql(
"SELECT z.price as price
FROM shipping_zone_prices z, items i
WHERE i.id = '#{item_id}'
AND z.weight_g > d.weight
ORDER BY z.weight_g asc limit 1")
end
end
这种作品。 SQL 完成了这项工作,但是当插入应用程序时,如下所示:
<%= @item.shipping_price %> Shipping
我得到以下显示:
[#<ShippingZonePrice price: 12>] Shipping
在此示例中,“12”是从数据库中提取的价格,并且是正确的。 @item.shipping_price.class 返回“数组”。尝试使用 [0](或任何其他整数)访问数组将返回空白。
有没有其他方法可以访问它,或者我错过了一些基本的东西?
由于您正在定义一个实例方法,我认为它应该返回price
如果存在或者nil
尝试这样的事情:
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
那么这应该适合你:
@item.shipping_price
The first.try(:price)
需要部分是因为find_by_sql
可能会返回一个空数组。如果你尝试做类似的事情first.price
在空数组上,您会得到一个异常,类似于NoMethodError: undefined method 'price' for nil:NilClass
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)