Rails搜索HABTM关系中的关联模型

时间:2013-09-17 20:20:25

标签: ruby-on-rails search find associations has-and-belongs-to-many

所有

我有一个课程,程序和员工数据库。一门课程已经并属于许多员工,一门课程已经属于许多课程。

我想创建一个返回与输入关键字匹配的所有课程的搜索功能。目前,我只搜索所有课程的字段,但我也希望返回某个课程和某些职员的课程,如果这些课程与搜索关键字匹配。换句话说,我也希望通过相关模型的字段进行搜索。这是我的代码:

class Course < ActiveRecord::Base
    has_and_belongs_to_many :programmes
    has_and_belongs_to_many :staffMembers

    def self.search(search)
        # wild cards in front and back
        search_condition = "%" + search + "%"
        find(:all, :conditions => ['name LIKE ? OR description LIKE ? OR goals LIKE ?',
        search_condition, search_condition, search_condition])
    end

end

在CoursesController中:

class CoursesController < ApplicationController

    def search
        @courses = Course.search params[:search]
    end
end

所有帮助表示赞赏!

1 个答案:

答案 0 :(得分:0)

这应该有效:

def self.search(search)
    # wild cards in front and back
    search_condition = "%" + search + "%"
    includes(:programmers, :staffMembers).find(:all, :conditions => ['name LIKE :search_condition OR description LIKE :search_condition OR goals LIKE search_condition OR programmers.name LIKE :search_conditions ...',
    :search_condition => search_condition])
end