1

我必须承认,我什至不确定我是否提出了正确的问题......

在我的应用程序中,我有一堆命名范围来构建更有效的查找。我无法上班的一个是:

=> 我想查找当前类别及其后代中的所有产品。我使用“祖先”gem 来构建树,它在类级别提供命名范围:

subtree_of(node)        #Subtree of node, node can be either a record or an id

所以我认为有一个这样的named_scope是个好主意:

named_scope :in_tree, :include => :category, :conditions => ['category in (?)', (subtree_of(@category)) ]

或者

named_scope :in_tree, :include => :category, :conditions => ['category in (?)', (@category.subtree_ids) ]

这两件事都适用于控制器和助手,但不适用于模型......当我没有弄错时,它归结为“@category”(我在控制器中定义了它)在模型中不可用。

有没有一种方法可以让它可用?

谢谢你的帮助!

瓦尔

4

1 回答 1

1

它在您的模型中不起作用,因为@category它是一个存在于您的控制器中的实例变量。您可以使用 lambda(匿名函数)将类别传递到命名范围:

named_scope :in_tree, lambda { |category| { :include => :category,
  :conditions => ['category in (?)', (subtree_of(category)) ] }}

或者

named_scope :in_tree, lambda { |category| { :include => :category,
  :conditions => ['category in (?)', (category.subtree_ids) ] }} 

现在在您的控制器/助手中,您可以使用命名范围使用Product.in_tree(@category).

于 2010-08-06T13:02:19.897 回答