【问题标题】:Rails search through associated models in HABTM relationRails 搜索 HABTM 关系中的关联模型
【发布时间】:2013-09-17 20:20:25
【问题描述】:

全部,

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

我想创建一个搜索功能,返回与输入关键字匹配的所有课程。目前,我只搜索所有课程的字段,但如果与搜索关键字匹配,我也想返回某个程序和某个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

感谢所有帮助!

【问题讨论】:

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


    【解决方案1】:

    这应该可行:

    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
    

    【讨论】:

    • 嗯,我现在加载页面时出现错误,但前提是我在条件中包含“programmes.name LIKE search_condition”之类的内容。否则没有错误并且工作正常(但仍然只在课程领域)。你确定这是对的?
    • 知道了:需要将名称更改为 course.name,将 staffMembers 更改为 staff_members。仍然没有完全习惯 Rails 的最后一个命名约定;我的模型与我的表不同。
    • 您可以在此处阅读有关命名约定的信息:itsignals.cascadia.com.au/?p=7。你设法让它工作了吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多