1

全て、

コース、プログラム、staffMembers のデータベースがあります。コースは多くのstaffMembersに属し、コースは多くのプログラムに属しています。

入力したキーワードに一致するすべてのコースを返す検索機能を作りたいです。現在、すべてのコースのフィールドを検索するだけですが、検索キーワードに一致する場合、特定のプログラムと特定のスタッフメンバーのコースも返したいと考えています。つまり、関連するモデルのフィールドも検索したいのです。これは私のコードです:

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 に答える