2017-02-06 24 views
0

請問我該如何顯示用戶的overall_ratings 爲0.我如何顯示overall_ratings爲0的用戶?目前 我可以顯示的0用戶收視率,但我不知道如何檢索 誰擁有等級零關於多態關係的SQL查詢 - Rails 4

模式

ActiveRecord::Schema.define(version: 20170202214851) do 

    create_table "rates", force: :cascade do |t| 
    t.integer "rater_id" 
    t.integer "rateable_id" 
    t.string "rateable_type" 
    t.float "stars",   null: false 
    t.string "dimension" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    end 

    add_index "rates", ["rateable_id", "rateable_type"], name: "index_rates_on_rateable_id_and_rateable_type" 
    add_index "rates", ["rater_id"], name: "index_rates_on_rater_id" 


    create_table "users", force: :cascade do |t| 
    t.string "email",       default: "", null: false 
    t.datetime "created_at",         null: false 
    t.datetime "updated_at",         null: false 
    t.string "firstname" 
    t.string "lastname" 
    end 
end 

rate.rb

的那些用戶(用戶信息)
class Rate < ActiveRecord::Base 
    belongs_to :rater, :class_name => "User" 
    belongs_to :rateable, :polymorphic => true 
end 

在我的user.rb模型中,我有方法overall_ratings,它顯示用戶的所有評級

方法user.rb

def overall_ratings 
    array = Rate.where(rateable_id: id, rateable_type: 'User') 
    stars = array.map {|user| user.stars } 
    star_count = stars.count 
    stars_total = stars.inject(0){|sum,x| sum + x } 
    score = stars_total/(star_count.nonzero? || 1) 
    end 

終端

2.3.0 :109 > user = User.find(20) 
2.3.0 :116 > user.overall_ratings 
    Rate Load (3.0ms) SELECT "rates".* FROM "rates" WHERE "rates"."rateable_id" = ? AND "rates"."rateable_type" = ? [["rateable_id", 20], ["rateable_type", "User"]] 
=> 3.5 

我試圖找出誰擁有等級爲0的用戶,但是我不確定 如何正確的SQL寫顯示此信息

users = User.all 
2.3.0 :189 > users.map(&:overall_ratings) 
=> [4.0, 3.75, 0, 3.0, 0, 0, 0, 0, 0, 0, 0, 0, 4.0, 0, 0, 3.0, 3.5, 0, 0, 0, 0] 


2.3.0 :197 > users.map(&:overall_ratings).delete_if{|i|i>=1} 
=> [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 

問題:我如何顯示overall_ratings爲0的用戶?目前我可以顯示評分爲0的用戶,但我不知道如何檢索評分爲零的用戶。你的幫助 將不勝感激

我不確定......我試圖下面,但我知道它的不正確

2.3.0 :203 > users_with_ratings_of_zero = users.map(&:overall_ratings).delete_if{|i|i>=1} 
=> [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 

2.3.0 :208 > users_with_ratings_of_zero.map(&:users) 
NoMethodError: undefined method `users' for 0:Fixnum 

回答

1
users_with_ratings_of_zero.map(&:users) 

這是失敗,因爲您已映射用戶的實際數量(評級)在這一行:

users_with_ratings_of_zero = users.map(&:overall_ratings) 

上面的代碼變成這個列表逼到號:[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]當你擁有的只是數字時,你無法取回用戶0

所以你需要做的是選擇用戶......而不是實際上將它們轉換爲數字。你需要不使用map

可以是這樣做的:

users_with_ratings_of_zero = users.select {|user| 0 == user.overall_ratings } 
+1

哇!非常感謝你......主要是爲了解釋答案。非常感謝! – ARTLoe

+1

非常歡迎。 :) –