こんにちは。
railsのhas_many throughの使い方に関して理解ができていないので、質問です。
User・Post・Commentモデルの3つのモデルがあります。
UserがPostに付属するCommentしたものを取得したい場合には、どのようにすればよろしいのでしょうか?
ざっくりとした関係性は、次のようなものになります。
User←→Post←→Comment 1..n 1..n
rails g model User name:string rails g model Post body: text user:references rails g model Comment body:text post:references user_id: integer
class User < ActiveRecord::Base has_many :posts has_many :comments, through: :posts end class Post < ActiveRecord::Base belongs_to :user has_many :comments end class Comment < ActiveRecord::Base belongs_to :post has_one :user, through: :post end
よく、上記のようなものになるかと思いますが、下記ではダメなのでしょうか?
class User < ActiveRecord::Base has_many :posts has_many :comments end
ここの差が理解できておりません。
よろしければご教授をお願いします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/03/01 03:53