【问题标题】:rails named_scope and :sourcerails named_scope 和 :source
【发布时间】:2010-01-08 21:50:54
【问题描述】:

我是 Rails 的初学者,

我们可以将:source 与命名范围一起使用吗?

我可以将它与 has_many 和其他关联一起使用

谢谢 标记

【问题讨论】:

    标签: ruby-on-rails scope named


    【解决方案1】:

    不,你不能,因为你不需要。 命名范围是其中定义的模型的一部分。

    class Post
      named_scope :published, :conditions => { :published => true }
    end
    

    但是,这并不妨碍您通过关联使用命名范围。

    class Category
      has_many :posts
    end
    
    category.posts # => all posts
    category.posts.published # only published posts
    

    【讨论】:

    • 然而,这种方法完全忽略了得墨忒耳法则,这是 has_many => through 的主要好处之一
    【解决方案2】:

    如果您可以在 find() 调用中使用它,通常您可以将它与命名范围一起使用。 find 的参数在文档 (http://apidock.com/rails/ActiveRecord/Base/find/class) 中逐项列出,但我不确定 source 是其中之一。据我所知,这是用于 has_many 关系之类的东西,而不是用于查找。

    但是,命名范围可以应用于关系,所以也许这就是您想要的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多