Skip to content

Instantly share code, notes, and snippets.

@kaineer
Last active July 20, 2019 13:31
Show Gist options
  • Save kaineer/631760 to your computer and use it in GitHub Desktop.
Save kaineer/631760 to your computer and use it in GitHub Desktop.
SQL-запросы (ActiveRecord)
class Author < ActiveRecord::Base
has_many :links, :class_name => "BookAuthorLink"
has_many :books, :class_name => "Book", :through => :links, :source => :books
# Получение списка авторов, не имеющих книг
def self.without_books
self.find_by_sql( "SELECT a.* FROM authors AS a " +
"LEFT OUTER JOIN book_author_links AS l ON l.author_id = author.id " +
"WHERE l.id IS NULL" )
# Использован один и тот же рецепт из "SQL. Сборник рецептов" Энтони Молинаро
end
end
class Book < ActiveRecord::Base
has_many :links, :class_name => "BookAuthorLink"
has_many :authors, :class_name => "Author", :through => :links, :source => :authors
# Получение списка книг, не имеющих авторов
def self.orphant_books
self.find( :all,
:joins => "LEFT OUTER JOIN book_author_links AS l ON l.book_id = books.id",
:conditions => "l.id IS NULL" )
# Решение на чистом ActiveRecord предполагает, если я правильно понимаю,
# проверку наличия авторов в цикле по всем книгам. Что выглядит довольно неприятно.
end
end
Book.orphant_books # -> книги без автора
Author.withoub_books # -> авторы, по которым нет книг
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment