TrestleAdmin / trestle-search

Search plugin for the Trestle admin framework
https://trestle.io
GNU Lesser General Public License v3.0
28 stars 11 forks source link

Search on author of a post/book #51

Closed rkumar closed 1 year ago

rkumar commented 1 year ago

I have a book/post table with author_id linking to author table (belongs_to :author). I am trying to add the author's name in the search but I keep getting errors because it seems that the author table is not getting linked in the query.

I've tried to add the authors table as follows:

  collection do
    # Set the default order when manual sorting is not applied
    Book.order(created_at: :desc).includes(:author)
  end
  collection do
    model.includes(:author)
  end

I've also tried to add in the author in the search query:

  search do |query|
    query ? collection.joins(:author).where("author.name ILIKE ?", "%#{query}%" ) : collection
  end

However I keep getting errors such as:

PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "author"
LINE 1: ...s" ON "authors"."id" = "books"."author_id" WHERE (author.nam...

How can I perform a search on a linked table ?

spohlenz commented 1 year ago

The where clause needs to refer to the actual table name rather than the association, so it should be pluralized:

collection.joins(:author).where("authors.name ILIKE ?", "%#{query}%")
rkumar commented 1 year ago

Thanks. Worked perfectly.