简体   繁体   中英

Rails search through associated models in HABTM relation

All,

I have a database of courses, programmes and staffMembers. A course has and belongs to many staffMembers and a course has and belongs to many programmes.

I want to make a search function that returns all courses that match the input keywords. Currently, I only search through all of the courses' fields, but I also want to return courses of a certain programme and of a certain staffMember if those match the search keywords. In other words, I want to search trough the associated models' fields as well. This is my code:

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

And in the CoursesController:

class CoursesController < ApplicationController

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

All help appreciated!

This should work:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM