如何显示'最近访问'?

时间:2013-12-17 02:37:18

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

所以我创建了一个包含用户个人资料的网络应用,用户可以根据兴趣搜索其他用户,以及发布+参加活动等。我怎样才能添加一个功能,用户可以看到谁'最近参观过某个活动?

event.rb

class Event < ActiveRecord::Base
  attr_accessible :title, :description, :location, :date, :time, :event_date

  acts_as_commentable
  has_many :comments, as: :commentable
  belongs_to :user
  has_many :event_participants, dependent: :destroy
  has_many :participants, through: :event_participants, source: :user

end

user.rb

class User < ActiveRecord::Base
  include PgSearch

  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :omniauthable,
         :omniauth_providers => [:facebook, :twitter, :linkedin]

  attr_accessible :email, :password, :password_confirmation, :zip, :gender, :remember_me, :first_name, :last_name,
                  :birthday, :current_password, :occupation, :address, :interests, :aboutme, :profile_image,
                  :photos_attributes, :age, :education, :ethnicity

  has_many :authorizations, :dependent => :destroy
  has_many :comments
  has_many :events
  has_many :photos, as: :attachable
  has_many :questions
  has_many :sent_messages, class_name: 'Message', foreign_key: :sender_id
  has_many :received_messages, class_name: 'Message', foreign_key: :receiver_id
  accepts_nested_attributes_for :photos
  mount_uploader :profile_image, ProfileImageUploader

end

event_participants.rb

class EventParticipant < ActiveRecord::Base
  attr_accessible :user_id, :event_id

  belongs_to :user
  belongs_to :event

  validates :user_id, uniqueness: {scope: :event_id}

end

events_controller snippit

class EventsController < ApplicationController
  before_filter :authenticate_user!

  def index
    @users = User.all
    @user = current_user
    @events = Event.all
    @interesting_people = @users.order("random()").first(5)

  end

  def new
    @event = Event.new
  end

  def create
    @event = current_user.events.new(event_params)

    respond_to do |format|
      if @event.save
        format.html { redirect_to :back, notice: 'Event was successfully created.' }
        format.json { render action: 'show', status: :created, location: @event }
        format.js
      else
        format.html { render action: 'new' }
        format.json { render json: @event.errors, status: :unprocessable_entity }
        format.js
      end
    end
  end

  def show
    @users = User.all
    @user = current_user
    @event = Event.find(params[:id])
    @commentable = @event
    @comment = @event.comments.new
    @interesting_people = @users.order("random()").first(5)
  end

先谢谢!

1 个答案:

答案 0 :(得分:2)

根据您的代码,看起来您可以执行以下操作:

@event.event_participants.include(:users).order('created_at desc').limit(X).map(&:user)

您也可以尝试不使用include

@event.event_participants.order('created_at desc').limit(X).map(&:user)

但那将会进行N + 1次查询。 join的效果会更好。

在上面的代码中,X将是您想要展示的参与者数量。