有人可以告诉我如何使用overall_ratings显示用户 0.如何显示
overall_ratings
为0的用户?目前 我可以显示用户评级为0,但我不知道如何检索 那些评级为零的用户(用户信息)
模式
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
,它显示用户的全部评级
方法
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
答案 0 :(得分: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 }