我有两个 model, Topic 和 User 如下
class Topic
include Mongoid::Document
include Mongoid::Timestamps
field :title
field :content
belongs_to :user
end
class User
include Mongoid::Document
field :username
has_many :topics, inverse_of: :user
end
现在我希望获取最后 10 条 Topic 的记录,并显示作者的用户名: topics = Topic.desc(:created_at).limit(10) topics.each do |topic| topic.user.username #报错 end
topic.user.username 这句报错 :( 错误为:undefined method `username' for nil:NilClass
topic.user 怎么会为 nil 呢?求解! (另外如果将查询改为 where 查询就没问题,topics = Topic.where(XXXXX) 这样就不会报错.)