【问题标题】:Rails - Refer to current object in modelRails - 引用模型中的当前对象
【发布时间】:2010-08-06 12:50:17
【问题描述】:

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

在我的应用程序中,我有一堆命名范围来构建更有效的查找。 我不能去工作的是这个:

=> 我想查找当前类别及其后代中的所有产品。我使用“祖先”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”(我在控制器中定义了它)在模型中不可用。

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

感谢您的帮助!

【问题讨论】:

    标签: ruby-on-rails class model named-scope


    【解决方案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) 来使用命名范围。

    【讨论】:

    • 非常感谢约翰!第二个选项就像一个魅力!我实际上在我的问题中犯了一个错误,它最终是这样的:named_scope :in_tree, lambda { |category| { :include => :category, :conditions => ['categories.id in (?)', (category.subtree_ids) ] }}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-20
    • 1970-01-01
    • 1970-01-01
    • 2012-02-06
    • 1970-01-01
    • 2012-11-07
    • 2012-04-28
    相关资源
    最近更新 更多