binarylogic / searchlogic

Searchlogic provides object based searching, common named scopes, and other useful tools.
http://rdoc.info/projects/binarylogic/searchlogic
MIT License
1.39k stars 133 forks source link

problem with MyModel.name_like_or_submodel_name_like #105

Closed lxneng closed 7 years ago

lxneng commented 14 years ago

For example, suppose I have an application with a has_one/belongs_to association between books and authors: class Book < ActiveRecord::Base has_one :author end class Author < ActiveRecord::Base belongs_to :book end create books and association to author $ script/console Loading development environment (Rails 2.3.5)

[ 'One', 'Two', 'Three' ].each do |title| ?> book = Book.create :title => title book.author = Author.create :name => "Author of Book #{title}" book.save end

create 2 books no associations

Book.create :title => 'Four' Book.create :title => 'Five'

>> Book.all.map(&:title)
=> ["One", "Two", "Three", "Four", "Five"]

then i using searchlogic to search the books , which book title or author name with some keywords

>> Book.title_like_or_author_name_like("o").map(&:title)
    Book Load (0.4ms)   SELECT "books".* FROM "books" INNER JOIN "authors" ON authors.book_id = books.id WHERE ((books.title LIKE '%o%') OR (authors.name LIKE   '%o%'))
=> ["One", "Two", "Three"]

I saw this code "INNER JOIN "authors" ON authors.book_id = books.id", it is means if book no author, the no author associate books will can't be searched, i want using the LEFT OUTER JOIN to do this search, but seems not found in searchlogic?

ps: then i write a named_scope

named_scope :title_like_or_author_name_like,
lambda {|n| {:conditions=>["books.title like  ? or  authors.name like ?",
  "%#{n}%","%#{n}%"], :joins => Book.left_outer_joins(:author)}}

>> Book.title_like_or_author_name_like("o").map(&:title)
Book Load (0.8ms)   SELECT "books".* FROM "books" LEFT OUTER JOIN "authors" ON authors.book_id = books.id WHERE (books.title like '%o%' or authors.name like '%o%') 
=> ["One", "Two", "Three", "Four"]