我关注了:http://railscasts.com/episodes/37-simple-search-form (尽管是更新版本)在我的应用程序上实现搜索。
现在当您搜索时,它会搜索 1 个表。如果该表链接到另一个表或连接表怎么办?有没有办法让它也搜索这些字段。
我这样说是因为目前我正在让它搜索一个表中的字段:
def self.search(search)
if search
where('LOWER (description) LIKE ? OR LOWER (title) LIKE ?', "%#{search}%" , "%#{search}%")
else
scoped
end
end
但我真的很希望它也能搜索链接表。有什么想法吗?
最佳答案
是的,您可以在查找中添加连接
# 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
好的,这将是 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
关于mysql - 修改 Rails 中的简单搜索以搜索链接数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4684915/