コメントを投稿するときに星評価(raty)とコメント文(content)を入力必須にして、コメント文は250字までにします。
comment.rb
validates :raty, numericality: {
less_than_or_equal_to: 5,
greater_than_or_equal_to: 1,
message: 'を入力してください。'
}
validates :content, presence: true, length: { maximum: 250 }
controllers/comment_controller.rb
def create
@comment = current_user.comments.new(comment_params)
@movie = Movie.find_by(params[:id])
if @comment.save
flash[:success] = 'コメントを投稿しました。'
redirect_to movie_path(@comment.movie_id)
else
flash.now[:danger] = 'コメントの投稿に失敗しました'
render "movies/show"
end
end
movies/_comment_form.html
<%= form_for @comment do |f| %>
<%= render 'layouts/error_messages', model: @comment %>
<div class="field" id="star">
<%= f.label :raty, "評価:" %>
<%= f.hidden_field :raty, id: :comment_star %>
<script>
$('#star').raty({
starOff: "<%= asset_path('star-off.png') %>",
starOn: "<%= asset_path('star-on.png') %>",
starHalf: '<%= asset_path('star-half.png') %>',
scoreName: 'comment[raty]',
half: true,
});
</script>
<%= f.hidden_field :movie_id, value: @movie.id %>
<%= f.label "コメント・感想" %>
<%= f.text_area :content, placeholder: "250文字以内で入力してください..." , onKeyUp: "countLength(value, 'textlength');",
class: "input-field", style: "margin-bottom:0;",required: true %>
<p id="textlength" style="text-align:right; margin-bottom:0;">0/250文字</p>
</div>
<%= f.submit '送信', class: "btn btn-outline-secondary" %>
<% end %>
<script type="text/javascript">
function countLength( text, field ) {
document.getElementById(field).innerHTML = text.length + "/250文字";
if (text.length>250) {
$('#textlength').css({
color:'#ff0000',
fontWeight:'bold'
});
}
else {
$('#textlength').css({
color:'#000000',
fontWeight:'normal'
});
}
}
</script>
こんな感じで文字数をカウントしてくれます。
これで星評価に何も入れなかったり、250字以上で投稿したりするとエラー文が出ます。
ただ、このエラー文が英語なので少し伝わりにくいかなと思うので、日本語に変更します。
gem 'rails-i18n'
bundle install
します。
config/application.rb
module ValidationMessageSample
class Application < Rails::Application
config.load_defaults 6.0
# 下の2行を追加する
config.i18n.default_locale = :ja
config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.yml').to_s]
end
end
そして翻訳ファイルを config/locales/models
配下に作成します。models
ディレクトリがない場合は、まずディレクトリを作ってから、その中にja.yml
ファイルを作成します。
config/locales/models/ja.yml
ja:
activerecord:
attributes:
comment:
raty: 星評価
content: 文字数
実際にエラーが出るようにコメントを投稿してみます。
無事日本語でエラー文が出ました!
参考: