Has_many通过查询

时间:2018-11-07 09:33:31

标签: ruby-on-rails model-associations

我有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 :(得分:0)

您忘记将作者和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}%")

答案 1 :(得分:0)

docs

  

如果要向随附的模型中添加条件,则必须   明确引用它们。

也就是说,您需要向查询中添加references(:authors),如下所示才能解决该错误

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

更新

  

无法将“ Book”加入名为“ author_books”的关联;也许你   拼错了吗?

您应将has_many :author_book替换为has_many :author_books,将through: :author_book替换为through: :author_books