やりたいこと
Railsアプリで、Facebookのようなお知らせ機能を作っています。
サービスとしては本のSNSで、誰かが自分のレビューをお気に入り登録すると、通知がくる機能です(メール通知ではなく、web上での表示されるお知らせ機能)
環境
Ruby 2.3.0
Rails 5.0.1
nginx 1.12.2
unicorn 5.3.1
現状
お気に入り登録したら、notificationsテーブルにレコードが追加され、お気に入りされた人がログインしたときに、新着通知がくるという部分は実装できました。
問題は、お気に入りを解除したときに、関連するお知らせレコードを削除する部分の実装です。
notification table
user_id -> お気に入りされたレビューを投稿した人
notified_by_id -> お気に入りをした人
review_id -> お気に入りされたレビュー
nottified_type -> "お気に入り"という文字列。今後、いいねやコメント時にもお知らせするように実装予定
read -> 未読/既読フラグ
モデルのリレーションは以下の通り。
class User < ApplicationRecord has_many :notifications, dependent: :destroy end class Favorite < ApplicationRecord has_many :notifications, dependent: :destroy end class Review < ApplicationRecord has_many :notifications, dependent: :destroy end class Notification < ApplicationRecord belongs_to :user belongs_to :notified_by, class_name: 'User' belongs_to :review end
favorites_controller.rbは、以下の通り。
class FavoritesController < ApplicationController before_action :require_user_logged_in after_action :create_notifications, only: [:create] def create review = Review.find(params[:review_id]) current_user.favorite(review) flash[:success] = 'お気に入りしました' redirect_to review end def destroy review = Review.find(params[:review_id]) current_user.unfavorite(review) flash[:success] = 'お気に入りから削除しました' redirect_to review end private def create_notifications @review = Review.find(params[:review_id]) return if @review.user.id == current_user.id Notification.create(user_id: @review.user.id, notified_by_id: current_user.id, review_id: @review.id, notified_type: 'お気に入り') end end
お気に入り登録後、解除しようとすると以下のようなエラーがでます。
アプローチ
notificationテーブルにフィールドを追加して、お気に入り登録時に、favorite_idを持たせれば、このリレーションでも削除できそうな気がするのですが、今後Likeやコメント時にもお知らせしたい場合に、notificationテーブルのフィールドが増えごちゃごちゃすることを懸念しています。
リレーションの張り方でうまく削除することはできないでしょうか?
アドバイスよろしくお願いいたします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。