LoginSignup
1
1

More than 5 years have passed since last update.

Railsのflashをhelperとboostrapで加工する

Posted at
なぜ??

RailsのViewをひさしぶりに触り(ほぼ初めてじゃない??)作成したが、
毎回書くのがめんどくさいのと、とりあえずhelperを触りたかったから。

以前

sample.erb
<% if.present? %>
  <div class="alert alert-success" role="alert">
    更新を完了しました。
  </div>
<% end %>

長い。。。ってか毎回これかくのがだるい。
しかもfailとか用途別にかくのだるい。毎回書くメリットがわからん。ってことで、

  • helper
  • bootstrap で対応することにした。

そもそもHeplerって??helper
単純にいうと、viewを簡単に書くmoduleの印象です。
scaffoldにもはいっており、

$ rails g helper XXX(helper name)

でhelperの作成ができます。

本題

flash_message用のhelperを作成して、erbに取り込む。

1. flash_message用のhelperを作成する

$ rails g helper flash_message
.
|- app
    |- helper
    |     |- flash_message_helper.rb

上記のようにhelperがflash_message_helper.rbが作成されます。

2. flash_message_helperの編集

参考
- stackoverflow

app.controller.rb
def show
end
def update
   redirect_to show_user_path, :flash => {:success => "更新しました" }
end
flash_message_helper.rb
module FlashMessageHelper
  def flash_message
    flash.map do | k, m |
      # k => success
      # m => 更新しました。
      content_tag :div, m, :id => k, :class => [:alert, "alert-#{k}"]
    end.join
  end
end

show.erb
<%= flash_message %>

完成しません。Stringではきだされて期待値通りにはいきません。
Stringをsafe_htmlでrenderingする必要があります。ので、最後に

show.erb
<%== flash_message %>

で完成。多分期待値通りに実装できます。

1
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
1
1