一つの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 %>
…
Read This Post