0

我试图找到一种在范围内设置虚拟属性的方法。背景是我有属于帐户的客户。客户可以购买销售商品。我有一张表customers_salesitem,它显示了哪些客户过去购买了哪些商品。

我想生成一个带有附加字段“类别”的销售项目列表,该列表将销售项目分类为客户购买的销售项目、不同客户从同一帐户购买的销售项目以及尚未购买的销售项目。任何人在帐户上购买。最终,我想将范围用于自动完成字段,但目前有点偏离。

我尝试了一些类似的东西:

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

尽管 SQL 已正确生成,但范围会返回没有类别的项目列表。

4

1 回答 1

0

尽管 where 方法和其他一些新的 Rails 3 查询方法可以用累积的影响链接起来,但有些不会合并。我不认为 select 方法合并。不幸的是,大部分新功能都没有很好的文档记录。选择的文档是

select(value = Proc.new)

我认为你需要的是:

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)          
}
于 2012-04-21T15:32:01.243 回答