1

全部,

我有一个包含课程、计划和员工的数据库。一门课程拥有并属于许多教职员工,一门课程拥有并属于许多课程。

我想做一个搜索功能,返回与输入关键字匹配的所有课程。目前,我只搜索所有课程的字段,但如果与搜索关键字匹配,我也想返回某个程序和某个staffMember的课程。换句话说,我也想搜索相关模型的字段。这是我的代码:

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

所有帮助表示赞赏!

4

1 回答 1

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
于 2013-09-17T20:29:12.227 回答