2011-01-13 42 views
1

我遵循:http://railscasts.com/episodes/37-simple-search-form(尽管是更新后的版本)来实现在我的应用程序上搜索。在rails中修改简单搜索以搜索链接的数据?

现在,当您搜索时,它会搜索1个表格。如果该表链接到另一个表或连接表,该怎么办?有没有办法让它搜索这些字段。

我这样说,是因为目前我有它从一个表中搜索到字段:

def self.search(search) 
    if search 
     where('LOWER (description) LIKE ? OR LOWER (title) LIKE ?', "%#{search}%" , "%#{search}%") 
    else 
     scoped 
    end 
    end 

但我真的很喜欢它来搜索链接的表也是如此。有任何想法吗?

回答

2

是的,你可以添加加入到寻找

# 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 

确定,这将是未来

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 
+0

确实找到(:所有)在rails3工作? – Elliot 2011-01-13 21:01:13

0

你可以看看searchlogic一个更好的例子(它有一个导轨3分支在github上)它使搜索更容易!