显示评分最高的对象。 Letsrate,Rails

时间:2014-07-05 17:04:41

标签: ruby-on-rails ruby ruby-on-rails-4

我有一些问题。我想在第5页上展示最好的酒店,但我不知道该怎么做。我维护使用了gem letrate。

schema.rb

  create_table "hotels", force: true do |t|
    t.string   "title"
    t.text     "description"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "author"
    t.boolean  "breakfast"
    t.decimal  "price"
    t.string   "avatar"
    t.integer  "address_id"
  end

  create_table "rates", force: true 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 "rating_caches", force: true do |t|
    t.integer  "cacheable_id"
    t.string   "cacheable_type"
    t.float    "avg",            null: false
    t.integer  "qty",            null: false
    t.string   "dimension"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "rating_caches", ["cacheable_id", "cacheable_type"], name: "index_rating_caches_on_cacheable_id_and_cacheable_type"

  create_table "users", force: true do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "users", ["email"], name: "index_users_on_email", unique: true
  add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true

end

rate.rb

class Rate < ActiveRecord::Base
  belongs_to :rater, :class_name => "User"
  belongs_to :rateable, :polymorphic => true

  #attr_accessible :rate, :dimension

end

hotel.rb

class Hotel < ActiveRecord::Base
  belongs_to :user
  belongs_to :address
  letsrate_rateable 'Rating'
  mount_uploader :avatar, AvatarUploader

  accepts_nested_attributes_for :address

end

user.rb

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  letsrate_rater
  has_many :hotels

end

我知道如何使用sql查询来做到这一点,但我刚开始学习RoR,我确信有更优雅的方式可以建议吗?

1 个答案:

答案 0 :(得分:1)

首先,您必须更改要降级的维度名称,否则它不会映射到您的表名称,并且此生成的宝石不会遵循rails约定。“/ p>

#Hotel
letsrate_rateable 'rating'

要按评分显示前n家酒店,请运行

Hotel.includes(:rating_average).order("rating_caches.avg DESC").limit(n)

您还必须在avg

中的rating_caches字段中添加索引

还可以查看letsrate_rateable方法。它只是定义了一些基于dimnesion名称的关联