rails 更新があったらバッジで知らせる機能
たまにはwebの話。まだまだrailsでwebサービス開発頑張ってます。このブログにもちょこちょこ技術っぽいこと書いていこうかと思います。
投稿系のwebサービスを作っており、自分向けに何かメッセージが発信されたり、コメントがつけられたりした時に、その旨を知らせるバッジ機能を追加しました。
仕組みは非常に簡単。
1、CommentModelにnewカラムを追加。
[shell]rails g migration add_new_to_comments new:boolean[/shell]
newカラムのデータ型はboolean。
2、newカラムのデフォルト値を設定。
[rails]class AddNewToComments < ActiveRecord::Migration def change add_column :comments, :new, :boolean, default: true, null: false end end[/rails]
これで追加されたコメントはnew=trueのデータを持っていることになります。
3、バッジを表示したい画面でnew=trueの個数をカウントして表示。もちろん自分だけ。
[html] <% if current_user = User.find(params[:id]) %> <%= Comment.where(new:true).count %> <% end %> [/html]
こんな感じ。
4、自分が開いたらnew=falseとなるようにControllerを修正。別のユーザーが開いても発動しないのがポイントですね。
[rails]def show @comment = Comment.find(params[:id]) if current_user = @comment.user @comment.new = false @comment.save end end[/rails]
みたいな感じでOK。
5,バッジのデザインをiphoneっぽく。
[css].badge{
float:right; background: -webkit-gradient(linear, left top, left bottom, from(#ee757b), to(#c80507)); background: -webkit-linear-gradient(top, #ee757b, #c80507); background: linear-gradient(to bottom, #ee757b, #c80507); background: gradient(linear, center top, center bottom, from(#ee757b), to(#c80507)); }[/css]
果たしてこんな情報でも誰かの参考になるのでしょうか。