railsで、2つのモデルをbelongs_toしているモデルのデータを作成したいです。
以下の3つのモデルがあったとします。
・User
・Article
・Comment
やりたいこととしては、Commentのデータを作成したいです。
UserとArticleは1対多の関係であり、ArticleとCommentも1対多です。
そして、モデルでの関連付けは以下のようになっています。
ruby
1#### User 2class User < ApplicationRecord 3 has_many :articles, foreign_key: :created_user_id 4 has_many :comments, foreign_key: :created_user_id 5end
ruby
1#### Article 2class Article < ApplicationRecord 3 belongs_to :user, foreign_key: :created_user_id 4 has_many :comments, foreign_key: :article_id 5end
ruby
1#### Comment 2class Comment < ApplicationRecord 3 belongs_to :user, foreign_key: :created_user_id 4 belongs_to :article, foreign_key: :article_id 5end
テーブル構造としては、
・User
id | user_name | created_at | updated_at |
---|
・Article
|id|article_id|article_detail|created_user_id|created_at|updated_at|
|:--|--:|--:|--:|--:|
・Comment
|id|comment_id|article_id|comment_detail|created_user_id|created_at|updated_at|
|:--|--:|--:|--:|--:|--:|
という風になっています。
たとえば、articleのデータを作成するときは
ruby
1user = User.find(1) 2article = user.articles.build
とすればいいのだと思うのですが、
Commentのように2つのモデルをbelongs_toしている場合はどうすればよいのでしょうか?
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/01/26 09:44
2020/01/26 09:53