Организовать счетчик просмотра страниц в определенном разделе Challenge в Ruby on Rails
Как лучшим образом изменить или дополнить показанный ниже код, чтобы получить подсчет и оценку количества просмотров Pin в определенном разделе Challenge и конкретным зарегистрированным текущим пользователем. Я начинающий и не хотелось бы использовать гемы (Rails 6.0.3).
Есть модели Pin, Challenge,соединительная таблица Position, User
class Pin < ApplicationRecord
belongs_to :user
has_many :positions, dependent: :destroy
has_many :challenges, through: :positions
has_one :counter, dependent: :destroy
end
class Challenge < ApplicationRecord
belongs_to :user
has_many :positions, dependent: :destroy
has_many :pins, through: :positions
end
class Position < ApplicationRecord
belongs_to :challenge
belongs_to :pin
end
class User < ApplicationRecord
has_many :pins, dependent: :destroy
has_many :challenges, dependent: :destroy
end
Для подсчёт количества просмотров я добавил модель Counter
class Counter < ApplicationRecord
belongs_to :pin
def counter_view_get
self.increment!(:counter_view)
self.save
end
end
Содержимое модели Counter
t.integer "counter_view", default: 0, null: false
t.bigint "pin_id", null: false
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["pin_id"], name: "index_counters_on_pin_id"
В контроллер Pins добавил
class PinsController < ApplicationController
def show
@pin.counter&.counter_view_get
end
def create
@pin = Pin.new(pin_params)
@pin.user = current_user
respond_to do |format|
if @pin.save
@pin.create_counter
…
end
end
def pin_params
params.require(:pin).permit(:title, :description, :challenge_ids => [], counter_attributes: [:counter_view ])
end
end
Для просмотра результатов добавил код в app/views/pins/index
<% @pins.each do |pin| %>
<%= pin.counter&.counter_view %>
<% end %>