渴望从Rails中的关联加载named_scope

时间:2009-03-28 13:53:47

标签: ruby-on-rails

有没有办法从关联中急切加载named_scope?

我有我的文章模型:

class Article < ActiveRecord::Base
  has_many :comments
end

和我的评论模型:

class Comment < ActiveRecord::Base
  belongs_to :article

  named_scope :approved, :conditions => { :approved => true }
  named_scope :unapproved, :conditions => { :approved => false }
end

我可以急切地加载文章的所有评论:

@article = Article.find(params[:id], :include => :comments)

我怎样才能这样做,但仅限于批准的评论?

2 个答案:

答案 0 :(得分:3)

目前它并不是内置于rails,但是Ryan Daigle创建了一个名为utility_scopes的插件,它添加了一个with()作用域,你可以这样做:

Article.approved.with(:comments)

博文:http://ryandaigle.com/articles/2008/8/20/named-scope-it-s-not-just-for-conditions-ya-know Github Repo:http://github.com/yfactorial/utility_scopes

<击>

[根据评论更新]

我的坏。我读得不够好。我认为没有任何东西可以让你像这样调用一个名为__scope的关联。我能想到的最接近的事情就是在Article:

上创建一个named_scope
class Article < ActiveRecord::Base
   named_scope :with_approved_comments, {:include => :comments, :conditions => ['comments.approved = ?', true]}
end

希望这有帮助。

答案 1 :(得分:1)

另一个答案对我不起作用,因为我必须在某些模型上加载这些关联的许多关联和关联。我发现我有两个选项,将关联更改为具有条件,从而为我想要的每个范围建立关联,或者将它们转换为具有has_many关联的类的方法。我需要做一些事情:

@newspaper = Newspaper.find params[:id], :include => {
  :articles => {
    :author => true,
    :source => true
  }
}

所以在我的例子中我改变了:

class Newspaper < ActiveRecord::Base
  has_many :articles
end

class Article
  belongs_to :newspaper
  belongs_to :author
  has_one :source

  named_scope :private, :conditions => { :private => true }
  named_scope :public, :conditions => { :private => false }
end

为:

class Newspaper < ActiveRecord::Base
  has_many :articles

  def articles_public
    articles.reject &:private
  end

  def articles_private
    articles.select &:private
  end
end

class Article
  belongs_to :newspaper
  belongs_to :author
  has_one :source
end

我发现这种方式更为可取,因为我现在可以在找到报纸时急切地加载文章,只需将所有article.private更改为article_private。我创建了两个协会,如:

has_many :articles_private, :class_name => 'Article', :conditions {:private => true}
has_many :articles_public, :class_name => 'Article', :conditions {:private => false}

在我需要所有相关文章的情况下,我不得不急于加载它们。