Action_textを使ってブログ投稿機能を作ろうとしているのですが、どうしても投稿ができません。
投稿しようとすると、
1 error prohibited this blog from being saved: Userを入力してください
となってしまい、保存ができません。
#問題のソースコード
ブログ投稿に関するコントローラー
class BlogsController < ApplicationController before_action :set_blog, only: %i[ show edit update destroy ] before_action :authenticate_user!, only: %i[new update create edit update destroy] # GET /blogs or /blogs.json def index @blogs = Blog.all end # GET /blogs/1 or /blogs/1.json def show end # GET /blogs/new def new @blog = Blog.new end # GET /blogs/1/edit def edit end # POST /blogs or /blogs.json def create @blog = Blog.new(blog_params) respond_to do |format| if @blog.save format.html { redirect_to @blog, notice: "Blog was successfully created." } format.json { render :show, status: :created, location: @blog } else format.html { render :new, status: :unprocessable_entity } format.json { render json: @blog.errors, status: :unprocessable_entity } end end end # PATCH/PUT /blogs/1 or /blogs/1.json def update respond_to do |format| if @blog.update(blog_params) format.html { redirect_to @blog, notice: "Blog was successfully updated." } format.json { render :show, status: :ok, location: @blog } else format.html { render :edit, status: :unprocessable_entity } format.json { render json: @blog.errors, status: :unprocessable_entity } end end end # DELETE /blogs/1 or /blogs/1.json def destroy @blog.destroy respond_to do |format| format.html { redirect_to blogs_url, notice: "Blog was successfully destroyed." } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_blog @blog = Blog.find(params[:id]) end # Only allow a list of trusted parameters through. def blog_params params.require(:blog).permit(:title,:body) end end
ブログ投稿に関するモデル
class Blog < ApplicationRecord has_rich_text :body belongs_to :user end
action_textに関するマイグレーションファイル
# This migration comes from action_text (originally 20180528164100) class CreateActionTextTables < ActiveRecord::Migration[6.0] def change create_table :action_text_rich_texts do |t| t.string :name, null: false t.string :title, null: false t.text :body, size: :long t.references :record, null: false, polymorphic: true, index: false t.references :user, foreign_key: true, null: false t.timestamps t.index [ :record_type, :record_id, :name ], name: "index_action_text_rich_texts_uniqueness", unique: true end end end
ブログに関するマイグレーションファイル
class CreateBlogs < ActiveRecord::Migration[6.0] def change create_table :blogs do |t| t.string :title t.string :body t.references :user, foreign_key: true, null: false t.timestamps end end end
ブログ投稿フォーム
<%= form_with(model: blog, local: true) do |form| %> <% if blog.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(blog.errors.count, "error") %> prohibited this blog from being saved:</h2> <ul> <% blog.errors.full_messages.each do |message| %> <li><%= message %></li> <% end %> </ul> </div> <% end %> <div class="field"> <%= form.label :タイトル%> <%= form.text_field :title%> <%= form.label :記事内容 %> <%= form.rich_text_area :body %> </div> <div class="actions"> <%= form.submit '投稿する', class:"button"%> </div> <% end %>
##エラーログ
app/controllers/blogs_controller.rb:25:in `create' web_1 | Started POST "/blogs" for 172.21.0.1 at 2021-04-09 04:07:34 +0000 web_1 | Cannot render console from 172.21.0.1! Allowed networks: 127.0.0.0/127.255.255.255, ::1 web_1 | (0.4ms) SET NAMES utf8, @@SESSION.sql_mode = CONCAT(CONCAT(@@sql_mode, ',STRICT_ALL_TABLES'), ',NO_AUTO_VALUE_ON_ZERO'), @@SESSION.sql_auto_is_null = 0, @@SESSION.wait_timeout = 2147483 web_1 | Processing by BlogsController#create as HTML web_1 | Parameters: {"authenticity_token"=>"bfwO2lxDbUi582//E7VFCXRmV7KP7HLmOg8btH68D3QVkRsimz2uRHei3Eg1BrRD7MfbX/+PEeliiRfg5C1/ag==", "blog"=>{"body"=>"<div>asdfasdfasdf</div>"}, "commit"=>"投稿する"} web_1 | User Load (0.7ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 ORDER BY `users`.`id` ASC LIMIT 1 web_1 | (0.4ms) BEGIN web_1 | ↳ app/controllers/blogs_controller.rb:28:in `block in create' web_1 | User Load (0.6ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1 web_1 | ↳ app/controllers/blogs_controller.rb:28:in `block in create' web_1 | Blog Create (0.8ms) INSERT INTO `blogs` (`user_id`, `created_at`, `updated_at`) VALUES (1, '2021-04-09 04:07:34.485874', '2021-04-09 04:07:34.485874') web_1 | ↳ app/controllers/blogs_controller.rb:28:in `block in create' web_1 | ActionText::RichText Create (1.1ms) INSERT INTO `action_text_rich_texts` (`name`, `body`, `record_type`, `record_id`, `created_at`, `updated_at`) VALUES ('body', '<div>asdfasdfasdf</div>', 'Blog', 1, '2021-04-09 04:07:34.706717', '2021-04-09 04:07:34.706717') web_1 | ↳ app/controllers/blogs_controller.rb:28:in `block in create' web_1 | (1.7ms) ROLLBACK web_1 | ↳ app/controllers/blogs_controller.rb:28:in `block in create' web_1 | Rendered /usr/local/bundle/gems/actiontext-6.0.3.6/app/views/action_text/content/_layout.html.erb (Duration: 1.8ms | Allocations: 314) web_1 | Rendered /usr/local/bundle/gems/actiontext-6.0.3.6/app/views/action_text/content/_layout.html.erb (Duration: 0.7ms | Allocations: 199) web_1 | Completed 500 Internal Server Error in 323ms (ActiveRecord: 6.5ms | Allocations: 37537)
##エラー画面のパラメーター
{"authenticity_token"=>"bfwO2lxDbUi582//E7VFCXRmV7KP7HLmOg8btH68D3QVkRsimz2uRHei3Eg1BrRD7MfbX/+PEeliiRfg5C1/ag==", "blog"=>{"body"=>"<div>asdfasdfasdf</div>"}, "commit"=>"投稿する"}
##エラーログ
[ActiveJob] [ActiveStorage::AnalyzeJob] [a108ccf5-a6f4-4942-a82d-c92d6232d759] (0.5ms) BEGIN web_1 | [ActiveJob] [ActiveStorage::AnalyzeJob] [a108ccf5-a6f4-4942-a82d-c92d6232d759] ActiveStorage::Blob Update (0.8ms) UPDATE `active_storage_blobs` SET `active_storage_blobs`.`metadata` = '{\"identified\":true,\"width\":3000,\"height\":4000,\"analyzed\":true}' WHERE `active_storage_blobs`.`id` = 1 web_1 | [ActiveJob] [ActiveStorage::AnalyzeJob] [a108ccf5-a6f4-4942-a82d-c92d6232d759] (1.9ms) COMMIT web_1 | [ActiveJob] [ActiveStorage::AnalyzeJob] [a108ccf5-a6f4-4942-a82d-c92d6232d759] Performed ActiveStorage::AnalyzeJob (Job ID: a108ccf5-a6f4-4942-a82d-c92d6232d759) from Async(active_storage_analysis) in 490.41ms web_1 | Started POST "/blogs" for 172.20.0.1 at 2021-04-09 13:57:09 +0000 web_1 | Cannot render console from 172.20.0.1! Allowed networks: 127.0.0.0/127.255.255.255, ::1 web_1 | Processing by BlogsController#create as HTML web_1 | Parameters: {"authenticity_token"=>"PgGSiA8pdNxDZLah7O6+zovBN8WqROOpLkBdICHAflLTRUkLyVteKvkQqNXdCRXdwSjbsjzPZUTnHFmwOwKY/A==", "blog"=>{"body"=>"<div>asdfasddfasdfd</div>"}, "commit"=>"投稿する"} web_1 | User Load (0.7ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 ORDER BY `users`.`id` ASC LIMIT 1 web_1 | (1.0ms) BEGIN web_1 | ↳ app/controllers/blogs_controller.rb:30:in `block in create' web_1 | User Load (0.6ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1 web_1 | ↳ app/controllers/blogs_controller.rb:30:in `block in create' web_1 | Blog Create (0.9ms) INSERT INTO `blogs` (`user_id`, `created_at`, `updated_at`) VALUES (1, '2021-04-09 13:57:09.087366', '2021-04-09 13:57:09.087366') web_1 | ↳ app/controllers/blogs_controller.rb:30:in `block in create' web_1 | ActionText::RichText Create (1.2ms) INSERT INTO `action_text_rich_texts` (`name`, `body`, `record_type`, `record_id`, `created_at`, `updated_at`) VALUES ('body', '<div>asdfasddfasdfd</div>', 'Blog', 1, '2021-04-09 13:57:09.094594', '2021-04-09 13:57:09.094594') web_1 | ↳ app/controllers/blogs_controller.rb:30:in `block in create' web_1 | (3.1ms) ROLLBACK web_1 | ↳ app/controllers/blogs_controller.rb:30:in `block in create' web_1 | Rendered /usr/local/bundle/gems/actiontext-6.0.3.6/app/views/action_text/content/_layout.html.erb (Duration: 0.9ms | Allocations: 211) web_1 | Rendered /usr/local/bundle/gems/actiontext-6.0.3.6/app/views/action_text/content/_layout.html.erb (Duration: 0.9ms | Allocations: 202) web_1 | Completed 500 Internal Server Error in 50ms (ActiveRecord: 7.5ms | Allocations: 10608) web_1 | web_1 | web_1 | web_1 | ActiveRecord::NotNullViolation (Mysql2::Error: Field 'user_id' doesn't have a default value): web_1 | web_1 | app/controllers/blogs_controller.rb:30:in `block in create' web_1 | app/controllers/blogs_controller.rb:29:in `create'
##やってみたこと
投稿をするときに日本語に対応していないからだめなのかなと思ったので、
gem 'rails-i18n'
を導入してみて、
/config/application.rbに、
config.i18n.default_locale = :ja
と
config.i18n.default_locale = :ja
の記述を加えてみたのですがだめでした。
そして、userに関するテーブル(以下、userテーブル)の情報を外部キーで参照させてみたのですがだめでした。
もう一つ試してみたこととしては、
@blog = current_user.blog_build(blog_params)
をblog_params
に入れてみたのですが、SystemStackErrorになってしまいました。
その後にcreateメソッドの一番上に書いたノオですが、だめでした。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。