mercredi 20 avril 2016

How to update time according to each click on recently viewed properties

i want to list recently viewed properties in logged in users dashboard.

So that i created a table called recentview with 3 fields ie; user_id ,property_id and view_time(will enter the current view time in table on click on that property). I tried by below code. but problem is it is entering same record multiple times on each click on the same property . what i need is if i click one property that should enter in table once and in the next clicks on that same property the view_time of the same property record should update.

<% if current_or_null_user.recentviewed? property %>
   <a href = "<%=recentviews_path(:id => property.id)%>" data-method="post" ><div class="img-blocks" style="background-image:url(<%= property.image.url(:thumbnail)%>)"></div></a>
 <% else %>
   <a href = "<%=recentviews_path(:id => property.id)%>" data-method="post" >   <div class="img-blocks" style="background-image:url(<%= property.image.url(:thumbnail)%>)"></div></a>
<%end%>

on click on property the that current time, property_id and user_id is storing in database my controller

class RecentviewsController < ApplicationController
  before_action :authenticate_user!, except: :create
  def create
    if user_signed_in?
      @views = Recentview.where(user_id: current_user.id, property_id: params[:id],view_time: Time.now.strftime("%d/%m/%Y %H:%M")).first_or_create
      redirect_to :back
    else
      redirect_to new_user_session_path, alert: 'Please login/Sign up to add this property to your favourite.'
    end
  end
end

my model

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  has_many :properties  
  has_many :recentviews
  has_many :recentviewed_properties, through: :recentviews, source: :property  
  
  def recentviewed? property
    recentviewed_properties.include? property
  end
end
                               
                               
                               
class Recentview < ActiveRecord::Base
  belongs_to :user
  belongs_to :property
end
class Property < ActiveRecord::Base
        belongs_to :user
        has_many :recentviews
        mount_uploader :image, ImageUploader

end

Please give a a solution to solve this issue. How i will update view_time in each click, and also how i will avoid multiple entries of same property in recentviews table Any help is appreciatable

Aucun commentaire:

Enregistrer un commentaire