I have an Invoice model that has an status_id attribute, this model belongs t开发者_StackOverflow社区o Status models.
The Invoice.status_id can be "0 => active" or "2 => closed" in the DB.
The thing is in my Status model i also have ":id => 1, :name => due", but this is only when the Invoice.payment_date is less than today.
So my question is how can i something like
i = Invoice.find(:first)
i.status.name # i need this to return due if the Invoice.status_id == 0 and
# Invoice.payment_date < Date.today
Obviously the above code is always returning the name based on the value Invoice.status_id, because the association is correct.
I hope it make sense and somebody can help me.
Thanks.
Is there a reason Status has to be a model? If not, I would make it a method like this:
class Invoice < ActiveRecord::Base
def status
if closed?
"closed"
elsif payment_date < Date.today
"due"
else
"active"
end
end
end
Then add a boolean field closed
to the invoices table.
I was looking the problem the wrong way. Once i read a little more of ActiveRecord and searchlogic, it came to me: named scope!!!
精彩评论