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

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

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

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

MySQL

MySQL(マイエスキューエル)は、TCX DataKonsultAB社などが開発するRDBMS(リレーショナルデータベースの管理システム)です。世界で最も人気の高いシステムで、オープンソースで開発されています。MySQLデータベースサーバは、高速性と信頼性があり、Linux、UNIX、Windowsなどの複数のプラットフォームで動作することができます。

Ruby on Rails

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

データベース

データベースとは、データの集合体を指します。また、そのデータの集合体の共用を可能にするシステムの意味を含めます

Q&A

解決済

1回答

1784閲覧

rails consoleからデータを保存しようとすると、id, created_at, updated_atがnilになってしまう。

jm_swim

総合スコア8

Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

MySQL

MySQL(マイエスキューエル)は、TCX DataKonsultAB社などが開発するRDBMS(リレーショナルデータベースの管理システム)です。世界で最も人気の高いシステムで、オープンソースで開発されています。MySQLデータベースサーバは、高速性と信頼性があり、Linux、UNIX、Windowsなどの複数のプラットフォームで動作することができます。

Ruby on Rails

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

データベース

データベースとは、データの集合体を指します。また、そのデータの集合体の共用を可能にするシステムの意味を含めます

0グッド

0クリップ

投稿2020/12/29 09:47

前提・実現したいこと

rails初心者です。現在チャットアプリを作成しています。(プログラミング、web周りの知識に関しても初心レベルです)
多対多の中間テーブルの部分を取り組んでおり、ユーザーと紐づいたルームの保存ができず困っています。ユーザー登録は2種類(user, coach)できるように設定しました。

発生している問題・エラーメッセージ

rails consoleでデータを新規追加した際に自動入力されるはずの
"id:"、"created_at"などの値が
"nil"になっています。

ビュー側から保存をするとルーム(debate)にid, name, created_at, update_atは保存されますが、中間テーブルにはルーム(debate)やid(user_id, coach_id)が保存されません。

エラーメッセージ

debate = Debate.new(name: "ルーム1", coach_ids: [1, 2])
debate.errors
<Debate:0x00007fe8c4400038 id: nil, name: "ルーム1", created_at: nil, updated_at: nil>
debate.save
=> false
debate.errors
=> #<ActiveModel::Errors:0x00007fe8baae33a0
@base=#<Debate:0x00007fe8c4400038 id: nil, name: "ルーム1", created_at: nil, updated_at: nil>,
@details={:coaches=>[{:error=>:invalid}, {:error=>:invalid}]},
@messages={:coaches=>["は不正な値です"]}>
debate.save!
ActiveRecord::RecordInvalid: バリデーションに失敗しました: Coachesは不正な値です

エラーメッセージを表示させたものを添付します。
全くの初心者でわかりません。お力添えをお願いします。

該当のソースコード

----マイグレーションファイル---- class CreateDebates < ActiveRecord::Migration[6.0] def change create_table :debates do |t| t.string :name, null: false t.timestamps end end end
# frozen_string_literal: true class DeviseCreateCoaches < ActiveRecord::Migration[6.0] def change create_table :coaches do |t| ## Database authenticatable t.string :name, null: false t.string :email, null: false, default: "" t.string :encrypted_password, null: false, default: "" t.string :teach_style, null: false ## Recoverable t.string :reset_password_token t.datetime :reset_password_sent_at ## Rememberable t.datetime :remember_created_at ## Trackable # t.integer :sign_in_count, default: 0, null: false # t.datetime :current_sign_in_at # t.datetime :last_sign_in_at # t.string :current_sign_in_ip # t.string :last_sign_in_ip ## Confirmable # t.string :confirmation_token # t.datetime :confirmed_at # t.datetime :confirmation_sent_at # t.string :unconfirmed_email # Only if using reconfirmable ## Lockable # t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts # t.string :unlock_token # Only if unlock strategy is :email or :both # t.datetime :locked_at t.timestamps null: false end add_index :coaches, :email, unique: true add_index :coaches, :reset_password_token, unique: true # add_index :coaches, :confirmation_token, unique: true # add_index :coaches, :unlock_token, unique: true end end
# frozen_string_literal: true class DeviseCreateUsers < ActiveRecord::Migration[6.0] def change create_table :users do |t| ## Database authenticatable t.string :name, null: false t.string :email, null: false, default: "" t.string :encrypted_password, null: false, default: "" t.string :style, null: false ## Recoverable t.string :reset_password_token t.datetime :reset_password_sent_at ## Rememberable t.datetime :remember_created_at ## Trackable # t.integer :sign_in_count, default: 0, null: false # t.datetime :current_sign_in_at # t.datetime :last_sign_in_at # t.string :current_sign_in_ip # t.string :last_sign_in_ip ## Confirmable # t.string :confirmation_token # t.datetime :confirmed_at # t.datetime :confirmation_sent_at # t.string :unconfirmed_email # Only if using reconfirmable ## Lockable # t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts # t.string :unlock_token # Only if unlock strategy is :email or :both # t.datetime :locked_at t.timestamps null: false end add_index :users, :email, unique: true add_index :users, :reset_password_token, unique: true # add_index :users, :confirmation_token, unique: true # add_index :users, :unlock_token, unique: true end end
class CreateDebateUsers < ActiveRecord::Migration[6.0] def change create_table :debate_users do |t| t.references :debate, foreign_key: true t.references :user, foreign_key: true t.timestamps end end end
class CreateDebateCoaches < ActiveRecord::Migration[6.0] def change create_table :debate_coaches do |t| t.references :debate, foreign_key: true t.references :coach, foreign_key: true t.timestamps end end end
----モデル---- class Debate < ApplicationRecord has_many :debate_users, dependent: :destroy has_many :users, through: :debate_users has_many :debate_coaches, dependent: :destroy has_many :coaches, through: :debate_coaches validates :name, presence: true end
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable has_many :debate_users, dependent: :destroy has_many :debates, through: :debate_users has_many :comments with_options presence: true do validates :name validates :style end PASSWORD_REGEX = /\A(?=.*?[a-z])(?=.*?\d)[a-z\d]+\z/i.freeze validates_format_of :password, with: PASSWORD_REGEX, message: 'は半角英数字を使用してください' end
class Coach < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable has_many :debate_coaches, dependent: :destroy has_many :debates, through: :debate_coaches has_many :comments has_many :boards with_options presence: true do validates :name validates :teach_style end PASSWORD_REGEX = /\A(?=.*?[a-z])(?=.*?\d)[a-z\d]+\z/i.freeze validates_format_of :password, with: PASSWORD_REGEX, message: 'は半角英数字を使用してください' end
class DebateUser < ApplicationRecord belongs_to :debate belongs_to :user has_many :comments end
class DebateCoach < ApplicationRecord belongs_to :debate belongs_to :coach end

よろしくお願いいたします。

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

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

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

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

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

guest

回答1

0

自己解決

class Debate < ApplicationRecord
has_many :debate_users, dependent: :destroy
has_many :users, through: :debate_users, validate: false
has_many :debate_coaches, dependent: :destroy
has_many :coaches, through: :debate_coaches, validate: false

validates :name, presence: true
end

太字の部分を追加したところ、解決しました。
直接的な原因はわかりませんが、、

投稿2020/12/29 10:43

jm_swim

総合スコア8

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

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

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.50%

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

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

質問する

関連した質問