简体   繁体   中英

Searchlogic on associations

I have the following associations:

class BookShelf {
  has_many :books
}

class Book {
  has_many :pages
  belongs_to :book_shelf
}

class Page {
  belongs_to :book
}

If I have a BookShelf object, how could I use searchlogic to search pages that belong to the books in the current book shelf?

Currently I'm using this one:

@bookshelf = BookShelf.find 1
@pages = Page.title_like("something").book_id_equals(@bookshelf.books.map { |book| book.id }).paginate :page => params[:page]

So the paginate part is just the use of will_paginate which is not really relavent.

The point is I think these lines of codes are somewhat ugly. Is there any improvements?

This should do the trick, and remove the need to map all the book ids into an array:

Page.title_like("something").book_bookshelf_id_equals(@bookshelf.id).paginate(:page => params[:page])

I tested it in one of my apps, where I had a similar model structure (Suburb -> Region -> State) using the following:

Suburb.name_like("east").region_state_name_like("vi").paginate(:page => 3)

Which seemed to do the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM