実現したいこと
Rails初心者です。
バリデーションが効かないため、解消したいです。
ご意見いただけますと幸いです。
■実装したいバリデーション
・複数のカラムのうち、最低1つの項目の入力が必要(全て空欄であればエラーを表示する)
・入力する場合は、1文字以上500文字以下
発生している問題・エラーメッセージ
全て空欄でもデータベースに登録できてしまいます。
コンソールで調べてもtrueと表示されてしまいます。
[11] pry(main)> comment = Comment.find(8) Comment Load (63.0ms) SELECT `comments`.* FROM `comments` WHERE `comments`.`id` = 8 LIMIT 1 => #<Comment:0x00007fc3bd5dc478 id: 8, created_at: Fri, 20 Jan 2023 19:47:58 UTC +00:00, updated_at: Fri, 20 Jan 2023 19:47:58 UTC +00:00, atmosphere: "", growth_potential: "", gap: "", treatment: "", reason_for_retirement: "", worker_id: 1, salon_id: 4> [12] pry(main)> comment.valid? => true
該当のソースコード
db>migrate>202301....create_comments.rb
1class CreateComments < ActiveRecord::Migration[6.0] 2 def change 3 create_table :comments do |t| 4 t.timestamps 5 t.text :atmosphere 6 t.text :growth_potential 7 t.text :gap 8 t.text :treatment 9 t.text :reason_for_retirement 10 t.references :worker, foreign_key: true 11 t.references :salon, foreign_key: true 12 end 13 end 14end 15
models>comment.rb
1class CommentValidator < ActiveModel::Validator 2 def validate(record) 3 items = [record.atmosphere, record.growth_potential, record.gap, record.treatment, record.reason_for_retirement] 4 return if items.any?(:present?) 5 record.errors[:base] << "どれか1つの項目は入力してください。" 6 end 7end 8 9class Comment < ApplicationRecord 10 include ActiveModel::Validations 11 validates_with CommentValidator 12 13 with_options length: { minimum: 1, maximum: 500 } do 14 validates :atmosphere 15 validates :growth_potential 16 validates :gap 17 validates :treatment 18 validates :reason_for_retirement 19 end 20 21 belongs to :worker 22 belongs to :salon 23 24end
controllers>comments_controller.rb
1 def create 2 @comment = Comment.new(comment_params) 3 if @comment.save 4 redirect_to root 5 else 6 render "comments/new" 7 end 8 end 9 10private 11 def comment_params 12 params.require(:comment) 13 .permit(:atmosphere, :growth_potential, :gap, :treatment, :reason_for_retirement) 14 .merge(worker_id: current_worker.id, salon_id: params[:salon_id]) 15 end
補足情報
https://teratail.com/questions/44399
参考にmodelを記載しました
前の質問が放置されてるような
https://teratail.com/questions/gcuf77j99lnj7s
