has_manyとbelongs_toの話
userとpostを結びつけたい場合、postはuserに紐付けられて、かつ、userがpostを複数持つ場合、
class User < ApplicationRecord has_many :posts, dependent: :destroy end class Post < ApplicationRecord belongs_to :user end
と記入することで、紐付けられる。
さらに、モデルを作る際に、
rails g model post user:references
とすることで、自動的にuser_idが作成され、さらに、作られたapp/model/post.rbには、belongs_to :userが追加されている。 できればこちらを使うようにしたい。
has_manyはvalidatesよりも上に記述されていないといけない。
参考
https://railsguides.jp/association_basics.html https://www.sejuku.net/blog/26617