2012-05-07 66 views
1

我對我的Tutor模型使用了acts_as_taggable_on gem。每位導師都有多種類型的標籤:班級(C201,M101),科目(化學,數學等)和背景(藝術,科學)。在Rails中搜索標籤的訂單

學生希望通過該順序與輔導教師匹配。例如:

如果有10位精確匹配的導師,請停止。

如果只有5位具有精確類匹配的導師,那麼找到包含主題匹配的下5個導師。

如果只有2位導師與確切的主題匹配,然後找到與後臺匹配的下3個。

我應該如何高效地編寫我的範圍或SQL查詢?一個天真的做法是爲每個學生,我必須計算所有導師的相關性,並相應地對他們進行排名。但這太低效了。

+0

什麼模型之間的關係? –

+0

你可以顯示一些示例數據來編寫SQL查詢嗎? – beck03076

+0

謝謝貝克和Aayush。請看我更新的問題。 – AdamNYC

回答

1

所以像Tutors.where(:類=> '值',:受試者=> ....)。ORDER_BY(:類,:主體,...)極限(10)

然後記住比賽的組合?

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