一つのHelperメソッドを作って、Modelに必須チェックが入ってるプロパティに対して必須マークの”*”を出力します。
まずapplicaton_helperにmark_requiredのメソッドを作ります。第一引数にはオブジェクト、第二引数はそのクラスのプロパティを渡します。
# application_helper.rb def mark_required(object, attribute) "*" if object.class.validators_on(attribute).map(&:class).include? ActiveModel::Validations::PresenceValidator end
viewのerbには下記のように@userインスタンス変数と:nameを渡します。もしUserモデルに:nameに対して必須バリデーションが存在すれば必須マークが出力されます。
<div class="field">
<%= f.label :name %><%=mark_required(@user, :name) %><br />
<%= f.text_field :name %>
</div>
参考リンク:http://railscasts.com/episodes/211-validations-in-rails-3
20110704更新
もしhtmlタグも一緒に出力したいときは、タグがエスケープされてしまいます。
module ApplicationHelper
def mark_required(object, attribute)
mark = "<span class='require_mark'>*</span>"
mark if object.class.validators_on(attribute).map(&:class).include? ActiveModel::Validations::PresenceValidator
end
end
<div class="field">
<%= f.label :name %><%=raw mark_required(@user, :name) %><br />
<%= f.text_field :name %>
</div>
この場合はrawを書けばエスケープされずにちゃんとHTMLタグが出力します。
You can leave a response, or trackback from your own site.
