3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Railsで簡単な通知機能(フォローされた時のみ)

Last updated at Posted at 2020-10-28

Railsでの簡単な通知機能です。(とりあえずフォローされた時のみ)

##ルーティングの設定

config/routes.rb
  resources :notifications, only: [:index]

##コントローラの作成

$ rails g controller notifications

##モデルの作成

$ rails g model Notification visitor_id:integer visited_id:integer
$ rails db:migrate

##モデルとアソシエーションの設定

app/models/user.rb
  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

  def create_notification_follow!(current_user)
    temp = Notification.where(["visitor_id = ? and visited_id = ? ",current_user.id, id])
    if temp.blank?
      notification = current_user.active_notifications.new(visited_id: id)
      notification.save if notification.valid?
    end
  end
app/models/notification.rb
  belongs_to :visitor, class_name: 'User', foreign_key: 'visitor_id'
  belongs_to :visited, class_name: 'User', foreign_key: 'visited_id'

##コントローラの設定

app/controllers/relationships_controller.rb
  def create
    @user = User.find(params[:user_id])
    current_user.follow(params[:user_id])
    @user.create_notification_follow!(current_user) #追記部分
    redirect_to request.referer
  end
app/controllers/notifications_controller.rb
  def index
    @notifications = current_user.passive_notifications.order(created_at: :DESC)
  end

##ビュー(通知一覧)の設定

app/views/notifications/index.html
<h1>おしらせ</h1>
<% if @notifications.exists? %>
  <% @notifications.each do |notification| %>
    <table>
      <tr>
        <td>
          <%= attachment_image_tag notification.visitor, :image, size: "50x50" %>
        </td>
        <td>
          <%= link_to user_path(notification.visitor) do %>
            <%= notification.visitor.name %>
          <% end %>
        </td>
        <td>
          からフォローされました。
        </td>
        <td>
          <%= " (#{time_ago_in_words(notification.created_at)}まえ)" %>
        </td>
      </tr>
    </table>
  <% end %>
<% else %>
  <p>おしらせはありません</p>
<% end %>
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?