RoR top100 pictures

I have to create a page with top100 photos by visiting, by comments ... but I don't know how. Someone help me!)

Mistake:

 undefined method `Visit' for <Photo::ActiveRecord

      

photo_controller

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

      

routes

 get 'photos/top100'  

      

schema

  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

      

photo.rb

  has_many :visits, dependent: :destroy

      

visit.rb

    belongs_to :photo
    belongs_to :user

      

+3


source to share


1 answer


Use SQL grouping and ordering:

# 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)

      

Learn more about ordering by invoice in SQL: SQL Order By Count

Pay attention to #includes(:photo)

- thus, the next call #map(&:photo)

will not generate N requests (only one to receive them).

Also, it looks like you didn't specify the relationship in your models, so add this line to visit.rb

:



belongs_to :photo

      

and this line - photo.rb

has_many :visits

      

unes you already have them.

-2


source







All Articles