Rails:从一个查询中搜索多个表

时间:2009-03-17 03:26:38

标签: ruby-on-rails search

如何以findpaginate方式编写条件语句,以便用户同时搜索ProjectProject Category个名称?

现在我的代码看起来像这样

@projects = Project.paginate :per_page => 20, :page => params[:page], :conditions => ['name LIKE ?', "%#{params[:search]}%"]

所以我还有Category表和name字段。如何在此搜索查询中将这两个name组合在一起?

2 个答案:

答案 0 :(得分:8)

假设您的Project模型has_many :categories

  

@projects = Project.paginate :per_page => 20, :page => params[:page], :joins => :categories, :conditions => ['projects.name LIKE ? OR categories.name LIKE ?', "%#{params[:search]}%", "%#{params[:search]}%"], :order => 'projects.id DESC'

根据需要更改上面的:order

答案 1 :(得分:0)

我愿意:

@categories = Category.find :conditions => ["name like ?", "%#{params[:search]}%"]

连接@projects和@categories,然后将结果用作最终搜索结果列表。