I have this class
class Invoice < ActiveRecord::Base
scope :last_with_number, -> (firm) {firm.invoices.where('number IS NOT NULL').order("number ASC").last}
end
When I run Invoice.last_with_number(Firm.first).number
in the console, I get this error
2.0.0p247 :001 > Invoice.last_with_number(Firm.first).number
Firm Load (1.5ms) SELECT "firms".* FROM "firms" ORDER BY "firms"."id" ASC LIMIT 1
Invoice Load (3.1ms) SELECT "invoices".* FROM "invoices" WHERE "invoices"."firm_id" = $1 AND (number IS NOT NULL) ORDER BY number DESC LIMIT 1 [["firm_id", 1]]
NoMethodError: Invoice Load (0.7ms) SELECT "invoices".* FROM "invoices"
undefined method `number' for #<ActiveRecord::Relation::ActiveRecord_Relation_Invoice:0x00000008793198>
But this spec passes
describe Invoice do
let(:firm) {FactoryGirl.create(:firm)}
let(:invoice1) {FactoryGirl.create(:invoice, customer:customer, firm:firm , number: 2)}
let(:invoice2) {FactoryGirl.create(:invoice, customer:customer, firm:firm , number:3)}
it 'gets the last numberd invoice for spesific firm' do
invoice1
invoice2
Invoice.last_with_number(firm).number.should eq 3
end
end
I can solve this problem by making a Invoice class method like this
def self.the_really_last(firm)
last_with_number(firm).last
end
And change the scope from
scope :last_with_number, -> (firm) {firm.invoices.where('number IS NOT NULL').order("number ASC").last}
to
scope :last_with_number, -> (firm) {firm.invoices.where('number IS NOT NULL').order("number ASC")}
This will work both places.
But, why is the scope behaving differently in the the spec and the console?