Rails 中的named_scope 与has_many 关联

发布于 2024-07-26 04:06:41 字数 873 浏览 5 评论 0原文

我正在尝试使用 Rails 的魔力来实现我认为相当复杂的查询,而代码中不会有很多难看的 SQL。

由于我的数据库处理的是相当专业的生物医学模型,我将把以下内容转化为更真实的场景。

我有一本模型书,它

has_many :chapters

属于_to :book 的章节

举例来说,章节有一个名称属性,名称可以是序言、简介和附录,一本书可以有一个名为序言的章节和一个名为简介的章节,但没有章节命名为附录。 事实上,

我希望找到所有包含前言和引言章节的书籍。

目前我有一个named_scope,如下

Book
  named_scope :has_chapter?, lambda { |chapter_names|
    condition_string_array = []
    chapter_names.size.times{condition_string_array << "chapters.name = ?"}
    condition_string = condition_string_array.join(" OR ")
    {:joins => [:chapters]  , :conditions => [condition_string, * chapter_names]}
  }

如果我调用Book. 有章节吗? [“序言”,“简介”] 这将为我找到所有具有名为序言或简介的章节的书籍。 我怎样才能做类似的事情,让我将章节的序言和引言分开?

我对 SQL 不太熟悉,所以不太确定需要哪种类型的联接以及这是否可以在命名范围内实现。

非常感谢

安东尼

I am trying to achieve what I think will be a fairly complex query using the magic of Rails without having lots of ugly looking SQL in the code.

Since my database is dealing with rather specialised biomedical models I'll translate the following to a more real world scenario.

I have a model Book that

has_many :chapters

and Chapter that

belongs_to :book

Say for instance Chapters have a name attribute and the names can be preface ,introduction and appendix, and a Book could have a Chapter named preface and a Chapter named introduction but no Chapter named appendix. In fact any combination of these

I am looking to find all Books that have both Chapters named preface and introduction.

At present I have a named_scope as follows

Book
  named_scope :has_chapter?, lambda { |chapter_names|
    condition_string_array = []
    chapter_names.size.times{condition_string_array << "chapters.name = ?"}
    condition_string = condition_string_array.join(" OR ")
    {:joins => [:chapters]  , :conditions => [condition_string, * chapter_names]}
  }

If I call Book. has_chapter? ["preface", "introduction"] this will find me all books that have either a Chapter named preface or introduction. How could I do a similar thing that would find me isolates that both Chapters preface and introduction?

I am not that familiar with SQL so am not quite sure what kind of join would be needed and whether this could be achieved in a named scope.

Many thanks

Anthony

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

嘦怹 2024-08-02 04:06:42

我正在寻找所有符合以下条件的书籍
两章均名为序言和
简介。

我使用 mysql,而不是 postgres,但我认为 postgres 支持子查询? 你可以尝试这样的事情:

class Book

  named_scope :has_preface, :conditions => "books.id IN (SELECT book_id FROM chapters WHERE chapters.name = 'preface')"
  named_scope :has_introduction, :conditions => "books.id IN (SELECT book_id FROM chapters WHERE chapters.name = 'introduction')"

end

然后:

Book.has_preface.has_introduction

I am looking to find all Books that
have both Chapters named preface and
introduction.

I use mysql, not postgres, but I assume postgres has support for sub-queries? You could try something like:

class Book

  named_scope :has_preface, :conditions => "books.id IN (SELECT book_id FROM chapters WHERE chapters.name = 'preface')"
  named_scope :has_introduction, :conditions => "books.id IN (SELECT book_id FROM chapters WHERE chapters.name = 'introduction')"

end

and then:

Book.has_preface.has_introduction
君勿笑 2024-08-02 04:06:42

我喜欢将代码压缩为

condition_string = Array.new(chapter_names.size, "chapters.name=?").join(" AND ")

,这确实适用于使用“OR”的连接。但是 AND 连接将不起作用,因为这意味着连接的单行中的 Chapters.name 必须同时是“前言”和“例如“简介”。

执行我原来的“OR”连接的一种更简洁的方法是

 named_scope :has_chapter?, lambda { | chapter_names |
   {:joins => [: chapters]  , :conditions => { :chapters => {:name => chapter_names}}}
 }

感谢 Duplex on Rails 论坛 (发布链接
为了解决我最初的问题,虽然 DUPLEX 建议这样

named_scope :has_chapters, lambda { |chapter_names|
  {:joins => :chapters  , :conditions => { :chapters => {:name => chapter_names}},
   :select => "books.*, COUNT(chapters.id) AS c_count",
   :group => "books.id", :having => "c_count = #{chapter_names.is_a?(Array) ? chapter_names.size : 1}" }
}

做,但这可能适用于某些 SQL 风格,但不适用于 PostgreSQL。 我必须使用以下

named_scope : has_chapter?, lambda { | chapter_names |
  {:joins => :chapters  , :conditions => { :chapters => {:name => chapter_names}},
   :select => "books.* , COUNT(chapters.id)",
   :group => Book.column_names.collect{|column_name| "books.#{column_name}"}.join(","), :having => "COUNT(chapters.id) = #{chapter_names.is_a?(Array) ? chapter_names.size : 1}" }
}

代码

Book.column_names.collect{|column_name| "books.#{column_name}"}.join(",")

是必需的,因为在 PostgreSQL 中,您无法选择带有 books.* 的所有列,然后按 books.* 进行分组。每列必须单独命名:(

I like the condensing of code to

condition_string = Array.new(chapter_names.size, "chapters.name=?").join(" AND ")

and this does indeed work for a join with "OR".However the AND join will not work since this means that chapters.name in a single row of a join has to be both 'preface' and 'introduction' for example.

An even neater way of doing my original "OR" join is

 named_scope :has_chapter?, lambda { | chapter_names |
   {:joins => [: chapters]  , :conditions => { :chapters => {:name => chapter_names}}}
 }

Thanks to Duplex on Rails Forum (Post link)
In order to achieve my original problem though DUPLEX suggested this

named_scope :has_chapters, lambda { |chapter_names|
  {:joins => :chapters  , :conditions => { :chapters => {:name => chapter_names}},
   :select => "books.*, COUNT(chapters.id) AS c_count",
   :group => "books.id", :having => "c_count = #{chapter_names.is_a?(Array) ? chapter_names.size : 1}" }
}

This may work in some flavour of SQL but not in PostgreSQL. I had to use the following

named_scope : has_chapter?, lambda { | chapter_names |
  {:joins => :chapters  , :conditions => { :chapters => {:name => chapter_names}},
   :select => "books.* , COUNT(chapters.id)",
   :group => Book.column_names.collect{|column_name| "books.#{column_name}"}.join(","), :having => "COUNT(chapters.id) = #{chapter_names.is_a?(Array) ? chapter_names.size : 1}" }
}

The code

Book.column_names.collect{|column_name| "books.#{column_name}"}.join(",")

is required because in PostgreSQL you can't select all columns with books.* and then GROUP BY books.* each column has to be named individually :(

你的呼吸 2024-08-02 04:06:42

我正在寻找所有符合以下条件的书籍
两章均名为序言和
介绍。

目前我有一个named_scope作为
如下

您可以在没有named_scope 的情况

class Book < ActiveRecord::Base
  has_many :chapters

  def self.has_chapter?(chapter_names)
    Chapter.find_all_by_name(chapter_names, :include => [:book]).map(&:book)
  end
end

I am looking to find all Books that
have both Chapters named preface and
introduction.

At present I have a named_scope as
follows

You can do this without a named_scope.

class Book < ActiveRecord::Base
  has_many :chapters

  def self.has_chapter?(chapter_names)
    Chapter.find_all_by_name(chapter_names, :include => [:book]).map(&:book)
  end
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文