railsのflashのよくあるお知らせ

railsのflashを使ってみて、今後同じような表現方法を使いそうだったのでメモ。

やりたいこと

controllerからflashメッセージがあったらタイプによって表現方法を変えたい。

コード例

controller

# 例えば
def create
@record = Record.new(record_params)
respond_to do |format|
if @record.save
flash[:success] = '新しい支払いを追加しました'
format.html { redirect_to records_path }
else
format.html { render :new }
end
end
end
haml
- if flash
- flash.each do |type, msg|
%p{ class: "flash #{type}" }
= "お知らせ: #{msg}"
css
p.flash{
display:none;
position: fixed;
top: 0;
width: 100%;
text-align: center;
color: #fff;
font-weight: bold;
padding: 10px;
&.success {
background-color: rgba(77, 188, 219, 0.8);
}
&.notice {
background-color: rgba(237, 221, 40, 0.8);
}
&.error {
background-color: rgba(219, 30, 20, 0.8);
}
&.info {
background-color: rgba(255, 255, 255, 0.8);
}
}
js
$ ->
$('p.flash').fadeIn 800, ->
setTimeout ->
$('p.flash').fadeOut(1000)
, 3000
すると
こんな感じになります。
良さですね。
overray