別のモデルを参照するモデルを作成したい:
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
しかし、モデルファイル(user.rb、post.rb)のルールに従ってmongoDBを機能させる方法がわかりません。
まず、モデルをスローするコマンド ラインを作成しました。
rails generate model User name:string
rails generate model Post content:string
次に、モデル ファイルを手動で編集しました。この行を追加しました
belongs_to :post
has_one :author, :class_name => 'User'
次に、1 つのアクションでコードを実行します。
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
他のすべては問題のままです。