简体   繁体   English

具有动态属性的Rails SQL查询

[英]Rails sql query with dynamic attribute

Say I have an ActiveRecord object that contains a quantity and a price stored in the database. 假设我有一个ActiveRecord对象,其中包含存储在数据库中的quantityprice

I have defined a accessor for the total_price: 我已经为total_price定义了一个访问器:

def total_price
 quantity * price
end

Now what if I want to use this dynamic "attribute" in multiple ActiveRecord query contexts? 现在,如果我想在多个ActiveRecord查询上下文中使用此动态“属性”怎么办? I might to sum on it, compute average, for multiple scope, etc. 我可能会对此进行总结,计算平均值,针对多个范围等。

What would be the best practices so that I don't have to repeat this quantity * price with ActiveRecord and if I don't want to denormalize by writing it in DB? 有什么最佳实践,这样我就不必用ActiveRecord重复此quantity * price ,并且如果我不想通过在DB中编写来进行非规范化处理?

Thanks! 谢谢!

Well we wanted to get caption (from join model) to appear on our associated image model (IE if you called @user.images , you'd be able to call image.caption (even though caption was in the join model) 好吧,我们想让caption (来自联接模型)出现在我们关联的image模型上(即,如果您调用@user.images ,则您可以调用image.caption (即使标题在image.caption模型中)

So we looked at this RailsCast (you'll benefit from around 6:40) which gave us some information about how you can use join to create more dynamic queries. 因此,我们看了看这个RailsCast (您将从6:40左右受益),它为我们提供了一些有关如何使用join创建更多动态查询的信息。 We ended up using this: 我们最终使用了这个:

has_many :images, -> { select("#{Image.table_name}.*, #{ImageMessage.table_name}.caption AS caption") }

I'm thinking you could use something similar for your request (include some SQL to create the pseudo column in the object). 我在想您可以为请求使用类似的东西(包括一些SQL在对象中创建伪列)。 Since it's the origin model, I'm thinking about a scope like this: 由于它是原始模型,因此我正在考虑以下范围:

default_scope select("(table.quantity * table.price) as total_price")

I assume price is stored in the database. 我假设价格存储在数据库中。 Is quantity stored in the database? 数量存储在数据库中吗? If both are stored, why not make total_price a database column as well? 如果两者都存储,为什么不也将total_price为数据库列? You can update total_price whenever you update the record.' 您可以在每次更新记录时更新total_price 。”

class Order < AR::Base
  before_update :update_total_price
  def update_total_price
    self[:total_price] = quantity * price
  end
end

Obviously you can do anything you would with an ordinary column, like Order.where("total_price > 1.0") and what-not. 显然,您可以对普通列执行任何操作,例如Order.where("total_price > 1.0")和不行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM