前提・実現したいこと
ruby on rails
で画像投稿アプリを作成しています。
コメントを10文字以内にしたいため、モデルでにバリデーションをかけ、
form_with
内で10文字より多いときにrender
でエラーメッセージを表示
させたい。
※ビューを遷移させず、form
の中に非同期表示させたい
10文字より多く投稿した場合、エラーにはなってDB登録はされないが
エラー表示が発生しない。
発生している問題・エラーメッセージ
投稿を実行しても、エラーは特になし。
Rendering layouts/_new.html.haml within layouts/application Rendered layouts/_new.html.haml within layouts/application (Duration: 1.9ms | Allocations: 2061) [Webpacker] Everything's up-to-date. Nothing to do Completed 200 OK in 29782ms (Views: 31.1ms | ActiveRecord: 6.4ms | Allocations: 27853)
該当のソースコード
◾️コントローラ blog_controller.rb
@post = Post.create(post_create_params) if @post.save redirect_to :post_image else render "layouts/_new" end
◾️ビュー(form部分)post_image.html.haml
.form_area = form_with model: @post do |form| .field = render 'layouts/new', model: @post = form.label :"comment(under 10 characters)" .br = form.text_field :title .br = form.label :image .br = form.file_field :image .br = form.submit "Post"
◾️ビュー(エラー表示用)_new.html.haml
-if @post.errors.any? .alert %ul -@post.errors.full_messages.each do |message| %li= message
試したこと
①
バリデーション:10文字以下ならDB保存される、10文字より多い場合されないことは確認。
②
form_with
にlocal:true
を入れる
→エラーメッセージはでるが、画面がlayouts/new
だけのビューに遷移してしまう。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/04/27 13:00