참조가 mongoid 모델 만들기 :내가 다른 참조 모델을 만들
class User
include Mongoid::Document
field :name, :type => String
belongs_to :post
end
class Post
include Mongoid::Document
field :content, :type => String
has_one :author, :class_name => 'User'
end
을하지만 MongoDB를 모델 파일에 대한 규칙에 따라 작동하게하는 방법을 혼란 스러워요 (user.rb, post.rb) .
모두 내가 만든 모델을 던져 명령 행의첫째 :
rails generate model User name:string
rails generate model Post content:string
그럼 난 수동으로 편집 모델 파일. 내가 한 행동에 코드를 실행 그런 다음이 줄
belongs_to :post
has_one :author, :class_name => 'User'
를 추가했습니다 :
post = Post.new
post.content = "text"
post.author = User.new
post.save!
가 데이터베이스에 그 결과 난 단지 내용 필드를 참조하십시오. 작성자 필드가 없습니다.
내가 뭘해야하고 내가 뭘 잘못하고 있니?
[답변] 나는 has_to와 belongs_to 장소를 혼동했다. 올바른 모델은 다음과 같습니다.
class User
include Mongoid::Document
field :name, :type => String
has_many :post
end
class Post
include Mongoid::Document
field :content, :type => String
belongs_to :author, :class_name => 'User'
end
기타 모든 질문은 계속됩니다. 내가 좋겠와
아 미안하지만 내재 된 개체에만 적용됩니다. 사실,이 트릭을 사용하여 "belongs_to"필드를 볼 수 있습니다 '포스트 = Post.new Post.find (게시물)' 나는 아직도 모든 "has_many"참조를 표시하는 방법을 찾고 있어요 –