0

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.

cpt_peter
  • 399
  • 2
  • 11

1 Answers1

0

Although the where method and some other of the new Rails 3 query methods can be chained with an accumulated affect, some do not merge. I don't think the select method merges. Unfortunately, much of this new functionality is not well documented. The documentation for select is

select(value = Proc.new)

I think what you will need is:

scope :previous_customer_purchase, lambda {
    |customer|
    select("*, 'Previous Customer Purchase' as category").
    where ("salesitems.id IN (SELECT customers_salesitems.salesitem_id FROM customers_salesitems WHERE customer_id = ?)",
        customer.id)          
}
Marlin Pierce
  • 9,931
  • 4
  • 30
  • 52