Created
April 25, 2012 21:57
-
-
Save topgenorth/2493840 to your computer and use it in GitHub Desktop.
Scope question
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class StorageFee < ActiveRecord::Base | |
OVERSTOCK_CHARGE_PER_ITEM = 0.02 # [TO20120202@0909] This is how much we charge/overstocked item. | |
belongs_to :publisher | |
# TODO[TO20120205@1954] Duplication with invoice, invoice_upload, sales_item | |
cattr_reader :per_page | |
@@per_page = 20 | |
scope :by_publisher_id, lambda { |id| where(:publisher_id => id) } | |
scope :to_date_on, lambda { |date| where(:to_date => date) } | |
scope :fee_summary, select("date(to_date) AS ordered_date, sum(overstock * 0.02) AS total_fees, sum(onhand) AS total_onhand, sum(overstock) AS total_overstock").group("date(to_date)") | |
### What do I have to do to this scope to hydrate the publisher? Or just JOIN in the publisher table? | |
scope :publisher_fee_summary, select("publisher_id, sum(soldqty) as total_sold, sum(overstock * 0.02) AS total_fees, sum(onhand) AS total_onhand, sum(overstock) AS total_overstock").group("publisher_id") | |
scope :ordered, order("storage_fees.to_date DESC") | |
scope :short_term, where("overstock > 0") | |
def total_fee | |
return 0.00 if (self.overstock.nil? || self.overstock < 0) | |
(OVERSTOCK_CHARGE_PER_ITEM * self.overstock).round(2) | |
end | |
comma do | |
to_date "Date" | |
publisher :abbrev => 'Publisher' | |
isbn13 "ISBN-13" | |
isbn10 "ISBN-10" | |
title "Title" | |
soldqty "Sold" | |
onhand "On Hand" | |
overstock "Overstock" | |
total_fee "Total Fee" | |
end | |
end |
Here are the details in the Rails guide:
http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I would suggest you use
scope :publisher_fee_summary, includes(:publisher).select("publisher_id, sum(soldqty) as total_sold, sum(overstock * 0.02) AS total_fees, sum(onhand) AS total_onhand, sum(overstock) AS total_overstock").group("publisher_id")
Note the includes in there which loads in the publisher model. You can also you join() but it introduces more SQL into this scope with I'd rather avoid if possible.