[RUBY] [Rails 6] Validation by belongs_to

Introduction

The error that occurred while creating the portfolio is described as a memorandum. We are creating a portfolio where you can search and browse articles related to subsidies.

environment

Ruby on Rails '6.0.0' Ruby '2.6.5'

error contents

An error regarding validation will occur. The error statement is as follows.

web_1  |   ↳ (pry):1:in `create'
web_1  |   Article Load (0.8ms)  SELECT `articles`.* FROM `articles` WHERE `articles`.`id` = 4 LIMIT 1
web_1  |   ↳ (pry):1:in `create'
web_1  |   User Load (0.7ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
web_1  |   ↳ (pry):1:in `create'
web_1  |    (0.3ms)  ROLLBACK
web_1  |   ↳ (pry):1:in `create'
web_1  | ActiveRecord::RecordInvalid:Validation failed:Please enter Company

What I learned ①: How to bind.pry in Docker environment

I have installed Docker in my development environment and used binding.pry to know the details of the error. However, it was the first time to execute a command in the Docker environment. This time, I referred to Run binding.pry on docker. Thank you very much.

% docker-compose up
% docker ps
%docker attach container ID or container name

By executing the above command, the debug mode was started and the error code could be confirmed.

What I learned ②: Using the save! Method

app/controllers/comments_controller.rb


  def create
    @comment = Comment.new(comment_params)
    if @comment.save
      ActionCable.server.broadcast 'comment_channel', content: @comment
    else
      render :new
    end
  end

This time, an error occurred in the create action part by the comment function described above. Even when I checked the log at the beginning, the details of the error statement were not specified and I could not understand it. Therefore, I referred to the article How to debug when an error occurs in the save method. Thank you very much. If the Rails save method couldn't be saved, it just returns "false" and you can't see the error log. By using "save!", The error content can be grasped.

8: def create
web_1  |      9:   @comment = Comment.new(comment_params)
web_1  |  => 10:   binding.pry
web_1  |     11:   if @comment.save
web_1  |     12:     ActionCable.server.broadcast 'comment_channel', content: @comment
web_1  |     13:   else
web_1  |     14:     render :new
web_1  |     15:   end
web_1  |     16: end
web_1  | 
[1] pry(#<CommentsController>)> 
[2] pry(#<CommentsController>)> @comment.save!
   (0.6ms)  BEGIN
web_1  |   ↳ (pry):1:in `create'
web_1  |   Article Load (0.8ms)  SELECT `articles`.* FROM `articles` WHERE `articles`.`id` = 4 LIMIT 1
web_1  |   ↳ (pry):1:in `create'
web_1  |   User Load (0.7ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
web_1  |   ↳ (pry):1:in `create'
web_1  |    (0.3ms)  ROLLBACK
web_1  |   ↳ (pry):1:in `create'
web_1  | ActiveRecord::RecordInvalid:Validation failed:Please enter Company

③ What I learned: About validation by belongs_to

At this point, I knew that it was a validation error. As a confirmation from here --Check the migration file and rewrite "null: false" --comment Check the model and rewrite the "presence: true" part.

I changed the above two and tried again, but the result did not change. So, (Personal note) Be careful with belongs_to when defining relationships in Rails 5 I arrived at this article.

When using "belongs_to", it was said that "required: true" is installed by default to prevent nil from being allowed in foreign keys related to belongs_to.

To solve

app/models/comments


class Comment < ApplicationRecord
  belongs_to :article
  belongs_to :user, optional: true
  belongs_to :company, optional: true

  validates :text, presence: true
end

By specifying ** optional: true **, we were able to allow "nil" and successfully resolved it! !! !!

in conclusion

We would like to thank the creators of the articles for their reference.

Recommended Posts

[Rails 6] Validation by belongs_to
[rails] Set validation
[Rails5] Rspec -validation-
[Rails] Customize devise validation
[Rails] Japanese longest surname (validation)
How to write Rails validation
[Rails] How to use validation
Ruby on Rails validation summary
Rails singular resource routing by resource
[Rails] I implemented the validation error message by asynchronous communication!
Summary of rails validation (for myself)
[Rails] Introduction of Rubocop by beginners
[Rails] Unexpected validation error in devise
[Rails] Regular batch processing by whenever
Rails form_with communicates Ajax by default
[Rails] Validation settings and Japanese localization
[Rails] Temporary retention of data by session
Rails enum Select prefecture by pull-down method
[Rails] Use validation on a specific controller
What Rails beginners learned by solving errors
[Rails] Image posting by CarrierWave [AWS EC2]
[Rails] Implementation of validation that maintains uniqueness
Rails validation and null: false Personal notes