やりたいこと
自作アプリ内で,以下のeach文を使って投稿を表示しているのですが,仮にですが表示上限を10個までとしたいです.
その際に,古いものから消えていくような仕様にしたいです.
<% @notifications.each do |notification| %>
<div class="notifications-index-item">
<% case notification.action %>
<% when "post" %>
<%= link_to(notification.post.dear, "/posts/#{notification.post.id}") %> <br>
<% when "reply" %>
<%= link_to(notification.reply.dear, "/replies/#{notification.reply.id}") %> <br>
<% else %>
<p>まだ来ていません</p>
<% end %>
</div>
<% end %>
今のままだと,おそらく無制限に投稿が表示されてしまうので,どなたかに教えていただきたいです.
追記
notification.rb
class Notification < ApplicationRecord
default_scope -> { order(created_at: :desc).limit(10) }
belongs_to :post, optional: true
belongs_to :reply, optional: true
belongs_to :visitor, class_name: 'User', foreign_key: 'visitor_id', optional: true
belongs_to :visited, class_name: 'User', foreign_key: 'visited_id', optional: true
end
notifications_controller.rb
class NotificationsController < ApplicationController
def index
@notifications=current_user.passive_notifications
#@notifications.where(checked: false).each do |notification|
#notification.update_attribute(:checked, "true")
#end
end
end
User.rb made by devise
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable,
:confirmable, :lockable, :timeoutable, :trackable
attribute :received_at, :datetime, default: -> { Time.now }
has_many :posts, dependent: :destroy
validates :name, presence: true
validates :birthday, presence: true
validates :received_at, presence: true
#アクティブで自分からの通知パッシブは他人から
has_many :active_notifications, class_name: "Notification", foreign_key: "visitor_id", dependent: :destroy
has_many :passive_notifications, class_name: "Notification", foreign_key: "visited_id", dependent: :destroy
end