【问题标题】:RoR top100 photosRoR 前 100 张照片
【发布时间】:2015-10-29 13:00:28
【问题描述】:

我必须通过访问、cmets 创建包含前 100 张照片的页面...但我不知道如何制作。请任何人帮助我:)

错误:

 undefined method `Visit' for <Photo::ActiveRecord

照片控制器

....
def top100
    @photos = Photo.all 
     @photos.visit.count(limit: 10)
  end

路线

 get 'photos/top100'  

架构

  create_table "visits", force: true do |t|
    t.integer  "photo_id"
    t.integer  "user_id"
    t.integer  "count",      default: 0
    t.datetime "created_at"
    t.datetime "updated_at"
  end

create_table "photos", force: true do |t|
    t.string   "name"
    t.text     "description"
    t.integer  "user_id"
    t.string   "image"
    t.string   "tags"
    t.string   "camera"
    t.string   "lens"
    t.hstore   "settings"
    t.integer  "im_rating",       default: 0
    t.integer  "im_visits",       default: 0
    t.integer  "im_votes",        default: 0
    t.boolean  "is_ban_comments", default: false
    t.datetime "created_at"
    t.datetime "updated_at"
  end

照片.rb

  has_many :visits, dependent: :destroy

访问.rb

    belongs_to :photo
    belongs_to :user

【问题讨论】:

  • 你希望通过这条线@photos.visit.count(limit: 10)得到什么?
  • 我理解你...但我不知道如何解决我的麻烦...你能帮帮我吗?我必须通过访问或投票显示评分最高的前 100 张照片...

标签: ruby-on-rails ruby


【解决方案1】:

使用 SQL 分组和排序:

# Top photos by visits
@top_photos = Visit.select("photo_id, COUNT(*) AS visit_count").includes(:photo).group(:photo_id).order("visit_count DESC").map(&:photo)

有关在 SQL 中按计数排序的更多信息:SQL Order By Count

注意#includes(:photo) - 这样下面的#map(&amp;:photo) 调用将不会产生 N 个查询(只需一个即可获取所有查询)。

另外,您似乎没有在模型中指定关系,所以将此行添加到visit.rb

belongs_to :photo

这一行到photo.rb

has_many :visits

除非你已经有了它们。

【讨论】:

  • 问题出在这里.map(&amp;:photo)
  • @Glupo 现在你开心吗?
  • 你的回答是对的,@EugZol,我错过了visits 中的user_id 列,这就是它没有意义的原因,所以我认为......
  • @RubyRacer 是的,抱歉太讽刺了,我对无缘无故收到太多反对票的事实感到非常不安。但现在我很好:D
  • 为什么要道歉?讽刺有什么不对吗?
猜你喜欢
  • 2013-02-06
  • 2016-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-28
  • 2014-03-19
  • 1970-01-01
相关资源
最近更新 更多