2012-06-12 187 views
1

在我的網站上,用戶有一個'待辦事項'列表。在測驗中獲得最低成績後,該測驗將從用戶的待辦事項中刪除。以下代碼適用於產品,但不適用於通過「商業關係」列出的任何測驗。MySQL查詢不起作用

def not_quizzed_things 
    taken_company_ids = quizzes_taken.select{|q| q.thing_type == 'BusinessRelationship'}.map{|q| q.thing_id}.uniq 
    conds = "business_relationships.from_company_id = ? and (business_relationships.legit_quiz_questions_count + c.legit_quiz_questions_count) > 0" 
    args = [company_id] 
    unless taken_company_ids.blank? 
    conds += " and c.id not in (?)" 
    args << taken_company_ids 
    end 

    quiz_companies = BusinessRelationship.find(:all, :joins => "join companies c on c.id = business_relationships.to_company_id", :conditions => [conds]+args, :order => "id", :limit => 0) 
    quiz_companies = [company] + quiz_companies unless company.legit_quiz_questions_count <= 0 || quizzes_taken.select{|q| q.thing_type == 'Company'}.map{|q| q.thing}.include?(company) 
    n = 20 - quiz_companies.size 

    taken_products_retailer_ids = quizzes_taken.select{|q| q.thing_type == 'ProductsRetailer'}.map{|q| q.thing_id}.uniq 
    conds = "products_retailers.company_id = ? and (p.legit_quiz_questions_count + products_retailers.legit_quiz_questions_count) > 0" 
    args = [company_id] 
    unless taken_products_retailer_ids.blank? 
    conds += " and products_retailers.id not in (?)" 
    args << taken_products_retailer_ids 
    end 
quiz_products_retailers = ProductsRetailer.find(:all, :joins => "join products p on p.id = products_retailers.product_id", :conditions => [conds]+args, :order => "id", :limit => n) 
quiz_companies + quiz_products_retailers 
end 

控制檯結果:

ruby-1.8.7-p352 :007 > y u.quizzes_taken.last 
--- !ruby/object:Quiz 
attributes: 
    thing_id: "213" 
    created_at: 2012-06-09 20:07:32 
    end_time: 2012-06-09 20:07:56 
    current_attempt_id: 
    thing_type: BusinessRelationship 
    updated_at: 2012-06-09 20:07:56 
    order: "2388,2389,2390,2391" 
    id: "467" 
    correct_count: "4" 
    user_id: "392" 
    attempt_count: "4" 
    start_time: 2012-06-09 20:07:32 
attributes_cache: {} 

任何想法或建議,不勝感激!

回答

0

我會查看您的調試窗口以查看發送到數據庫的確切SQL,並查看您的查詢未按預期發佈的原因。從您的數據庫返回到您的代碼。