0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Rails コメント投稿機能 コード解説 (モデルの作成について)

0
Last updated at Posted at 2022-02-24
user.rb
  has_many :comments

1つのUserオブジェクトに対して複数のcommentオブジェクトが存在するという意味になります。
また、has_many関連付けを宣言する場合、相手のモデル名は「複数形」で指定する必要があります。
has_many関連付け

post.rb
  has_many :comments

1つのPostオブジェクトに対して複数のcommentオブジェクトが存在するという意味になります。
投稿は複数のコメントを持つことを意味します。
has_many関連付け

comment.rb
class Comment < ApplicationRecord
  validates :content, { presence: true, length: { maximum: 100 } }
  belongs_to :user
  belongs_to :post
end

2行目のバリデーションはCommentにcontent属性がない場合に無効であることを知らせます
3行目・4行目
あるモデルでbelongs_to関連付けを行なうと、他方のモデルとの間に「1対1」のつながりが設定されます。
commentモデルとuserモデルとの間は「1対1」のつながり、
commentモデルとuserモデルとの間は「1対1」のつながりということになります。
belongs_to関連付け

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?