Has_many через запрос - PullRequest
       22

Has_many через запрос

0 голосов
/ 07 ноября 2018

У меня есть 2 модели (Книги и Авторы) и третья таблица, соединяющая их (has_many через ассоциацию).

Я пытаюсь реализовать поиск в моем приложении и выполнить запрос по обеим таблицам. Мой запрос выглядит так, и я не могу понять проблему:

Book.includes(:authors, :author_books).where("books.title LIKE ? OR authors.name = LIKE ?", "%#{book}%", "%#{book}%")

Это ошибка, которую я запускаю:

PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "authors"
SELECT "books".* FROM "books" WHERE (books.title LIKE '%Harry%' OR authors.name = LIKE '%Harry%')

Вот моя схема трех таблиц:

create_table "author_books", force: :cascade do |t|
    t.bigint "author_id"
    t.bigint "book_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["author_id"], name: "index_author_books_on_author_id"
    t.index ["book_id"], name: "index_author_books_on_book_id"
  end

  create_table "authors", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "books", force: :cascade do |t|
    t.string "title"
    t.text "description"
    t.string "image"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "rating"
    t.string "critics"
    t.float "price"
  end

author_book.rb

class AuthorBook < ApplicationRecord
  validates_presence_of :author, :book
  belongs_to :author
  belongs_to :book
end

author.rb

class Author < ApplicationRecord
  validates :name, uniqueness: true
  has_many :author_book
  has_many :books, through: :author_book
end

book.rb

class Book < ApplicationRecord
  validates :title, uniqueness: true, :case_sensitive => false
  has_many :author_book
  has_many :authors, through: :author_book
  has_many :categories, through: :category_book

  def self.search_book(book)
    if book
      Book.joins(:authors, :author_books).includes(:authors, :author_books).where("books.title LIKE ? OR authors.name = LIKE ?", "%#{book}%", "%#{book}%")
    end
  end  
end

Я вызываю этот метод search_book в моем контроллере книг следующим образом:

def search
    @books = Book.search_book(params[:book])
end

Помогите, пожалуйста? Спасибо!

Ответы [ 2 ]

0 голосов
/ 07 ноября 2018

Из документов

Если вы хотите добавить условия к включенным моделям, вам придется явно ссылаться на них.

Тем не менее, вам нужно добавить references(:authors) к вашему запросу, как показано ниже, чтобы устранить ошибку

Book.includes(:authors, :author_books).where("books.title LIKE ? OR authors.name = LIKE ?", "%#{book}%", "%#{book}%").references(:authors)

Обновление:

Невозможно присоединить «Книгу» к ассоциации с именем «author_books»; может ты с ошибкой?

Вы должны заменить has_many :author_book на has_many :author_books и through: :author_book на through: :author_books

0 голосов
/ 07 ноября 2018

Вы забыли присоединить авторов и author_books к своим отношениям. includes загружает :author и :author_books, но в отдельных запросах.

Попробуйте это:

Book.joins(:authors, :author_books).includes(:authors, :author_books).where("books.title LIKE ? OR authors.name = LIKE ?", "%#{book}%", "%#{book}%")
...