0
@post = Post.first.comments.build(content: "bla", user: @user)
을 수행하고 @user.comments
을 통해 검색 할 때 아무 것도 나타나지 않습니다. 하지만 @post.comments
으로 해보면 댓글이 나열됩니다. @user.comments
과 @post.comments
모두 내 댓글을 어떻게 볼 수 있습니까?레일 5 : 2 모델을 통해 모델을 어떻게 볼 수 있습니까?
class Post < ApplicationRecord
belongs_to :user
has_many :comments
end
내 사용자 모델
class User < ApplicationRecord
has_many :posts
has_many :comments
end
코멘트 모델 사용자의 게시물과 관련된 모든 게시물의 의견을 얻을 수
class Comment < ApplicationRecord
belongs_to :user
belongs_to :post
end
'.build'는 새로운 레코드를 인스턴스화하기 만합니다. 레코드를 DB에 저장하지 않습니다. '.new'의 별명입니다. 그래서'@ user.comments'을 할 때 데이터베이스를 쿼리하고 메모리에서만 생성 한 새로운 레코드를 신경 쓰지 않습니다. – max
'@comment = Post.first.comments.create (content : "bla", user : @user); @comment == @ user.comments.last' 다른 한편으로는 당신이 찾고있는 것을 성취 할 것입니다. – max
thx @max 왜 작동했는지 모르겠지만'build'가 작동하지 않았다. – chaosfirebit