开发者

Modifying simple search in rails to search linked data?

I followed: http://railscasts.com/episodes/37-simple-search-form (albeit the updated version) to implement searching on my app.

Right now when you search, it searches 1 table. What if that table is linked to another table, or a join table? Is there a way to make it search those fields as well.

I say this, because currently I'm having it search to fields from one table:

def self.search(search)
    if search
      where('LOWER (description) LIKE ? OR LOWER (title) LIKE ?', "%#{search}%" , "%#{search}%")
    else
      scoped
    end
  end
开发者_如何学C

but I'd really like it to search a linked table as well. Any ideas?


Yes, you can add joins to the find

# models/project.rb
def self.search(search)
  if search
    find(:all, :joins => :other_model, :conditions => ['projects.name LIKE :search or other_models.name LIKE :search', {:search => "%#{search}%"}])
  else
    find(:all)
  end
end

OK, this would be a better example for the future

  def self.search(search)
      if search
        joins(:other_model).where('LOWER (projects.description) LIKE ? or LOWER (other_models.name) LIKE ?', "%#{search}%", "%#{search}%")
      else
        scoped
      end
    end


You could take a look at searchlogic (it has a rails 3 branch on github) it makes searching alot easier!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜