如何根据最近查看的属性的每次点击更新时间

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

我想在登录用户仪表板中列出最近查看的属性。

所以我创建了一个 table 名为 recentview 的 3 个字段,即; user_id、property_id 和 view_time(单击 属性 时将在 table 中输入当前观看时间)。 我尝试了以下代码。但问题是每次点击同一个 属性 都会多次输入同一条记录。我需要的是,如果我点击一个 属性 应该进入 table 一次,然后在下一次点击相同的 属性 和相同的 属性 的 view_time记录应该更新。

<% 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%>

单击 属性 当前时间,property_id 和 user_id 存储在数据库中 我的控制器

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

我的模型

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

请给出一个解决方案来解决这个问题。 我将如何在每次点击时更新 view_time,以及我将如何避免在最近的视图 table 中出现多个相同 属性 的条目 感谢任何帮助table

@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

在这一行中(为了便于阅读,现在分为 3 行)您将始终在数据库中创建一个新的 RecentView 记录,因为 Time.now 将始终具有一个新值(与现有记录相比).


也许你可以试试:

@recent_view = Recentview.where(user_id: current_user.id, property_id: params[:id]).first_or_create

然后一旦您找到记录或创建了一个新记录,您就可以将 view_time 设置为:

@recent_view.update(view_time: Time.now.strftime("%d/%m/%Y %H:%M")) 

使用这种方法,您应该会无意中创建多个记录。