I am trying to find a way of setting a virtual attribute in a scope. The background is I have customers who belong to accounts. Customers can purchase salesitems. I have a table customers_salesitem that shows which customers have bought what items in the past.
I would like to generate a list of salesitems with an additional field 'category' that categorises the salesitems into those that have been bought by the customer, those that have been bought by a different customer from the same account, and those that have not been bought by anyone on the account. Ultimately, I want to use the scope for an autocomplete field but that is a little off at the moment.
I have tried a few things along the lines of:
class Salesitem < ActiveRecord::Base
has_many :customers_salesitems
scope :previous_customer_purchase, lambda {
|customer|
select("*").
select("'Previous Customer Purchase' as category").
where ("salesitems.id IN (SELECT customers_salesitems.salesitem_id FROM customers_salesitems WHERE customer_id = ?)",
customer.id)
}
def category
@category
end
def category=(value)
@category = @attributes["category"] = value
end
end
Although the SQL is correctly generated the scope returns an item list without category.