开发者

Rails 3 - SQL query in a more "rails way"

I want to know if you know how to write the following sql query in a more "rails way"

UPDATE  buy_order_detail
SET saldo = saldo - detail_purchase.cantidad
FROM purchase_detail
           INNER JOIN purchase ON purchase.id =
purchase_detail.purchase_id
           INNER JOIN waybill ON waybill.id =
purchase.waybill开发者_开发问答_id
           INNER JOIN buy_order ON buy_order.id =
waybill.order_id
           INNER JOIN buy_order_detail ON buy_order.id =
buy_order_detail.order_id
WHERE purchase_detail.product_id = buy_order_detail.product_id 

I've tried something like this, in the "DetailPurchase model"

def after_create
    pchs = Purchase.find(self.purchase_id)
    wbl = Waybill.find(pchs.waybill_id)
    bdr = BuyOrder.find(wbl.buy_order_id)
   BuyOrderDetail.find_by_buy_order_id(bdr.id).where(:product_id => self.product_id).update_attribute(:saldo, buy_order_detail.saldo - cantidad)
  end

But when I check the value "saldo", it always keep the same original value


Writing the question using the Rails Way, would implore that you

  1. write Models
  2. use Associations between the models to define their relations
  3. call upon Model.find() with some conditions to generate the SQL (automatically and out-of-sight)

All these steps (and more) are explained in the Getting Started with Rails documentation

With Ruby on Rails one (normally) does not generate SQL directly. But data from a database is modeled by (duh) Models. These models are used by Rails to retrieve the requested information from the database. Basically, you could say that each Model corresponds with a table in the database (at least for simple situations).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜