[英]Rails search through associated models in HABTM relation
All, 所有,
I have a database of courses, programmes and staffMembers. 我有一个课程,计划和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. 当前,我只搜索所有课程的字段,但是如果与搜索关键字匹配的话,我还想返回某个程序和某个staffMember的课程。 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: 在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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.