1
1

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 5 years have passed since last update.

基本的な1対多の関連付け

Posted at

post一つにたくさんのcommentができるいわゆる1:nの関係を構築する。(postは完成している前提)
①commnetモデル作成

rails g model Comment name:string body:text post:references

最後のpost:referencesを忘れない!
するとmodel/comment.rbが生成され、以下の記述が。

model/comment.rb
belongs_to :post

「commentはpostに属していますよ」ということ

②model/post.rbにを追記

qiita.rb
has_many :comments, :dependent => :destroy

・こんどは「postはたくさんのcommentを持っていますよ」ということ(だから”comments”と複数形)

・:dependent => :destroyは「親であるpostが削除されたら、それに関連していたcommmentも削除します」ということ

③resources :postsにresources :commentsをネストさせる

routes.rb
resources :posts do
  resources :comments
 end
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?