第一步是创建一个新的模型和控制器的通知
$ rails g model Notification post:references comment:references user:references read:boolean
$ rake db:migrate
$ rails g controller Notifications index
一旦这样做了,下一步就是添加has_many:通知用户,Post和Comment模型。
一旦做到这一点,下面的代码添加到评论模式:
after_create :create_notification
private
def create_notification
@post = Post.find_by(self.post_id)
@user = User.find_by(@post.user_id).id
Notification.create(
post_id: self.post_id,
user_id: @user,
comment_id: self,
read: false
)
end
上面的代码中创建一次评论中创建的通知。 下一步是编辑通知控制器,以便通知可以删除,并且用户可以将通知标为已读:
def index
@notifications = current_user.notications
@notifications.each do |notification|
notification.update_attribute(:checked, true)
end
end
def destroy
@notification = Notification.find(params[:id])
@notification.destroy
redirect_to :back
end
接下来要做的是建立一种方法来删除通知时评论被删除:
def destroy
@comment = Comment.find(params[:id])
@notification = Notification.where(:comment_id => @comment.id)
if @notification.nil?
@notification.destroy
end
@comment.destroy
redirect_to :back
end
最后要做的是创造一些看法。你可以做任何你想做的事