質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.46%
Ruby on Rails 6

Ruby on Rails 6は、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Q&A

解決済

2回答

766閲覧

Action_textを使ってブログ投稿できる機能をつけようと思ったのですが、1 error prohibited this blog from being saved:になってしまう

kawasaki4563

総合スコア32

Ruby on Rails 6

Ruby on Rails 6は、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

0グッド

0クリップ

投稿2021/04/08 00:39

編集2021/04/10 03:24

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メソッドの一番上に書いたノオですが、だめでした。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答2

0

自己解決

自己解決できました。
CreateActionTextTablesという名前のテーブルに
t.references :user, foreign_key: true, null: falseを書いていたのでそちらを削除したらできました。
Mysql2::Error: Field 'user_id' doesn't have a default value
となってしまっていたのは、ActionTextテーブルには、もともとユーザー情報がないからだとおもいます。
ブログを投稿するところにしか行かないのだと思います。

投稿2021/04/10 06:45

kawasaki4563

総合スコア32

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

0

belongs_to :user なので user_id に値が有ることが必須です。
エラーメッセージにそう出てますよね。
params.require(:blog).permit(:title,:body).merge(user_id: current_user.id)
とするか
@blog = current_user.blog_build(blog_params)
としてください。

投稿2021/04/08 23:13

winterboum

総合スコア23397

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

kawasaki4563

2021/04/09 04:09

params.require(:blog).permit(:title,:body).merge(user_id: current_user.id) とやってみたのですが、 Mysql2::Error: Field 'user_id' doesn't have a default value というエラーになってしまいました。 マイグレーションファイルの方にもuserの外部キーを参照するように記述はあるのですができませんでした。 モデルの方にある `belongs_to user`にoptional: trueをつけてみたのですがだめでした。
winterboum

2021/04/09 08:05

database側に user_id が null false になっているでしょうから、Rails側でoptional: trueしてもだめです。 params.require(:blog).permit(:title,:body).merge(user_id: current_user.id) とやってみて Mysql2::Error: Field 'user_id' doesn't have a default value というのが解せません。 1) それどこに書きました? 2) loginしてますか?
kawasaki4563

2021/04/09 10:38

1)blog_paramsのストロングパラメーターに書きました。 その後にブログ投稿ボタンを押したらそうなってしまいました。 2)はい、ログインしています。
kawasaki4563

2021/04/09 13:59 編集

了解です エラーログの方載せました
kawasaki4563

2021/04/10 05:33 編集

blogにどうやらuser_idが入っていないみたいですね。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.46%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問