加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – Rails 3.2:如何从一系列儿童中找到所有父母

发布时间:2020-12-17 02:03:57 所属栏目:百科 来源:网络整理
导读:鉴于“书籍”的集合,找到所有“作者”(没有重复)的最佳方法是什么? 所以,假设我们有一个经典的关联: class Author ActiveRecord::Base has_many :booksendclass Book ActiveRecord::Base belongs_to :authorend 我现在这样做的方式是这样的: @books = Boo
鉴于“书籍”的集合,找到所有“作者”(没有重复)的最佳方法是什么?

所以,假设我们有一个经典的关联:

class Author < ActiveRecord::Base
  has_many :books
end

class Book < ActiveRecord::Base
  belongs_to :author
end

我现在这样做的方式是这样的:

@books = Book.where("some condition")
@authors = Author.where(:id => @books.map(&:author_id))

有没有更好的方法呢?

解决方法

这是一种方式:

@books = Book.where("some condition").includes(:author)
@authors = @books.map(&:author).compact.uniq

说明:

> include会热切地加载作者,所以每当一本书想要它的作者时你就不会得到可怕的O(n)db调用…> uniq删除重复的作者(在这种情况下你可能想使用inverse_of选项不确定)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读