1

我为我的 Tutor 模型使用了acts_as_taggable_on gem。每个导师都有多种类型的标签:课程(C201、M101)、学科(化学、数学等)和背景(艺术、科学)。

学生希望按该顺序与导师匹配。例如:

如果有 10 位导师与班级完全匹配,则停止。

如果只有 5 位导师与班级完全匹配,则查找下 5 位与主题匹配的导师。

如果只有 2 位导师与主题完全匹配,则查找下 3 位与背景匹配的导师。

我应该如何有效地编写我的范围或 SQL 查询?一种天真的方法是针对每个学生,我必须计算所有导师的相关性,并相应地对它们进行排名。但这太低效了。

4

2 回答 2

1

所以像 Tutors.where(:class => 'value', :subject => ....).order_by(:class, :subject, ...).limit(10)

然后记住匹配的组合?

于 2012-05-17T21:00:15.787 回答
1

模型:

require 'active_record'

ActiveRecord::Base.logger = Logger.new(STDERR)
ActiveRecord::Base.colorize_logging = false

ActiveRecord::Base.establish_connection(
    :adapter => 'sqlite3',
    :dbfile  => ':memory:'
)

ActiveRecord::Schema.define do

    create_table :College do |table|
        table.column :name, :string
    end

end

class College < ActiveRecord::Base
    acts_as_taggable_on :roles, :courses, :subjects, :backgrounds
end

college = College.new(:name => 'Kerry Green', :role_list => 'student', :course_list => 'CM201', :subject_list => 'Biochemistry', :background_list = 'Science')
college.save

college = College.new(:name => 'Brian Jones', :role_list => 'student', :course_list => 'CM101', :subject_list => 'Chemistry', :background_list = 'Science')
college.save

college = College.new(:name => 'Lewis Smith', :role_list => 'student', :course_list => 'AR102', :subject_list => 'Fine Art', :background_list = 'Arts')
college.save

college = College.new(:name => 'Evan Hunt', :role_list => 'tutor', :course_list => 'CM201, CM101', :subject_list => 'Chemistry, Biochemistry', :background_list = 'Science')
college.save

college = College.new(:name => 'Stuart White', :role_list => 'tutor', :course_list => 'CM201', :subject_list => 'Biochemistry', :background_list = 'Science')
college.save

college = College.new(:name => 'Wendy Jones', :role_list => 'tutor', :course_list => 'CM201', :subject_list => 'Biochemistry', :background_list = 'Science')
college.save

标签匹配:

# find CM201 courses

@student = College.find( :name => 'Brian Jones')

@byCourse = @student.find_related_on_courses.find_tagged_with('tutor', :on=> :roles) 
 if @byCourse.length >= 10 
    // rule 1
else  
  @bySubject = @student.find_related_on_subjects.find_tagged_with('tutor', :on=> :roles) 
  if @byCourse.length >= 5 && @bySubject.length >= 5
   // rule 2
  else
     @byBackground = @student.find_related_on_backgrounds.find_tagged_with('tutor', :on=> :roles) 
     if @bySubject.length >= 2 && @byBackground.length >= 3
        // rule 3
     else
       // no match
     end
  end
end
于 2012-05-17T21:35:40.087 回答