class method or named_scope?

Posted by Hadi on Stack Overflow See other posts from Stack Overflow or by Hadi
Published on 2010-06-03T04:13:06Z Indexed on 2010/06/03 4:24 UTC
Read the original article Hit count: 360

Filed under:
|

i would like to have your opinion in a project i am currently working on.

class Product has_many :orders end

class Order
  attr_accessor :deliverable # to contain temporary data on how many items can be delivered for this order
  belongs_to :product
end

somehow i want to have

Order.all_deliverable

that will calculate the Product's quantity, subtract from list of Orders until the Product is empty or there is no more Order for this Product

to illustrate

  Product A, quantity: 20
  Product B, quantity: 0
  Order 1, require Product A, quantity: 12
  Order 2, require Product B, quantity: 10
  Order 3, require Product A, quantity: 100

so if i call Order.all_deliverable, it will give

Order 1, deliverable:12
Order 3, deliverable: 8 #(20-12)

i have been thinking on using named_scope, but i think the logic will be too complex to be put in a named_scope. Any suggestion?

the pseudo code for all_deliverable will be something like this: go to each orders find the remaining quantity for specific product deduct the product to max amount of order, if product is not enough, add the maximum product add to the order end

From what i read around in the web, named_scope deal mostly like find and have not many method calling and looping.

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about activerecord