Be careful when using multiple articles

Number of reference articles

Qiita has many attractive articles, so I tend to refer to many articles. However, since there are various ways of writing depending on the article, if you refer to multiple articles without understanding the contents, it tends to cause an error. Therefore, when implementing one function, only one article should be referred to.

If you refer to multiple articles ...

For example, if you want to create a DM function https://qiita.com/tenitiumai/items/3d9466d7a24197f690bb  Let's assume that you referred to.

model/message.rb


class Message < ApplicationRecord
  belongs_to :user
  belongs_to :room
end

Suppose you had code like this in user.rb in the above article. However, because I referred to another article, in reality

model/message.rb


class User < ApplicationRecord
  validate :messages, presence: true
  has_many :messages, dependent: :destroy
  has_many :entries, dependent: :destroy
end

Suppose it was described as.

Even if this one does not work, if you keep writing multiple unnecessary codes, it will cause an unexpected error. It is not necessary to bind messages with validate here. This is because it is strange to write code that always requests a message even though it is a message model.

models/user.rb


  has_many :comments, dependent: :destroy 
  has_many :entries, dependent: :destroy
  has_many :messages, dependent: :destroy
  has_many :rooms, dependent: :destroy

This also has an unnecessary part. In the DM function, user arrives at room via the intermediate table entries, so there is no need to write has_many: rooms. As mentioned above, when the code piles up unnecessarily![Screenshot 2020-09-09 14.20.39.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com /0/650686/c6603d57-f746-46bb-14cd-7ba85f39fa7b.png) You will get an error like this. In particular, the model part is the basis for creating controllers and acitons, so it is safe to refrain from writing unnecessary code on the model page as much as possible.

Summary

This error is caused by not understanding the basics properly. It's easy for beginners to do it, so it's safe to keep it as one as possible when referring to the article (if you can understand the basics, you can refer to more than one ...).

Recommended Posts

Be careful when using multiple articles
Be careful when using rails_semantic_logger with unicorn
Be careful of initialization timing when using MessageEncryptor with Rails 5.2 / 6.0
Be careful when upgrading Tomcat on a Web system using Oracle
Be careful when omitting return in Ruby
Be careful with requests and responses when using the Serverless Framework in Java
[Rails] When using ajax, be aware of "CSRF measures".
Things to be aware of when using devise's lockable
[Java10] Be careful of using var and generics together
Error when using rails capybara
Detailed tips when using Rails