前提
Ruby on Rails で記事の投稿機能を作ろうとしています。ログイン機能はDeviceを導入してある状態です。ログインしたユーザーが記事を投稿できるようにしたいです。主な使用技術は以下です。
ruby "3.1.2"
gem "rails", "~> 7.0.3", ">= 7.0.3.1"
gem 'bulma-rails'
gem 'devise'
実現したいこと
- createアクションを正常に作動させる。
発生している問題・エラーメッセージ
submitボタンを押すと、DBに反映されて欲しいのですが、反映されず、フォーム画面が再レンダリングされます。ターミナルは以下のようにnewアクションが呼び出されてるような表示です。
Started GET "/articles/new?authenticity_token=[FILTERED]&article***&body***&commit=Submit" for ::1 Processing by ArticlesController#new as HTML Parameters: {"authenticity_token"=>"[FILTERED]", "article"=>{"title"=>"タイトル", "body"=>"本文"}, "commit"=>"Submit"} User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 7], ["LIMIT", 1]]
該当のソースコード
articles_controller.rb
1class ArticlesController < ApplicationController 2 before_action :authenticate_user!, only: [:new, :create, :edit, :update, :destroy] 3 4 def new 5 @article = current_user.articles.build 6 end 7 8 def create 9 @article = current_user.articles.build(article_params) 10 if @article.save! 11 flash[:success] = "Article created" 12 redirect_to root_url 13 end 14 end 15 16 private 17 18 def article_params 19 params.require(:article).permit(:title, :body) 20 end 21end
_form.html.erb
1<%= form_with(model: @article, local: true) do |f| %> 2 <%= render 'shared/error_messages', object: f.object %> 3 <div class="field"> 4 <%= f.label :title, class: "label" %> 5 <%= f.text_area :title, class: "input", placeholder: "Title" %> 6 </div> 7 <div class="field"> 8 <%= f.label :body, class: "label" %> 9 <%= f.text_area :body, class: "textarea", placeholder: "Body", rows: "10" %> 10 </div> 11 <div class="actions"> 12 <%= f.submit "Submit", class: "button is-primary" %> 13 </div> 14<% end %>
試したこと
save!メソッドとbyebugを使ってみましたが再レンダリングされるのみです。articleモデルによるバリデーションを消してもダメでした。
初歩的な質問だとは思いますが、どなたか教えていただけるとありがたいです!
追記
フォームの送信先を指定するために以下のように書き換えてみましたが、効果がありませんでした、、、
他に試してみるべきことございましたら教えていただきたいです。
<%= form_with(url: articles_path, method: :post, local: true) do |f| %> <- ここ <div class="field"> <%= f.label :title, class: "label" %> <%= f.text_area :title, class: "input", placeholder: "Title" %> </div> <div class="field"> <%= f.label :body, class: "label" %> <%= f.text_area :body, class: "textarea", placeholder: "Body", rows: "10" %> </div> <div class="actions"> <%= f.submit "Submit", class: "button is-primary" %> </div> <% end %>