新手问题 mongoid 获取结果集出现奇怪的问题~~~ 求支招!

newnewnew · 2013年04月23日 · 最后由 newnewnew 回复于 2013年04月23日 · 2465 次阅读

我有两个 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) 这样就不会报错.)

你确定 mongoid 的 has_many 和 belongs_to 是你这样写的么

@Sunnyroger 额 有问题么?

mongoid 官方给你的例子,我也不太熟悉你看一看

class Artist
  include Mongoid::Document
  field :name, type: String
  embeds_many :instruments
end

class Instrument
  include Mongoid::Document
  field :name, type: String
  embedded_in :artist
end

syd = Artist.where(name: "Syd Vicious").between(age: 18..25).first
syd.instruments.create(name: "Bass")
syd.with(database: "bands", session: "backup").save!

#3 楼 @Sunnyroger 你这个例子我记得是声明内嵌文档用的。 楼主的代码好像没错,mongodb 没怎么用了不大清楚,等楼下解答。

@Sunnyroger 是的,@saiga 说得没错,我并不是做内嵌,我只是做一个 1-N 的关联关系。

测了一下,没有问题

require('mongoid')
Mongoid.load!("./mongoid.yml",:development)

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

user = User.create({username: 'test'})
Topic.create({title: 'topic', content:"content", user:user})

topics = Topic.desc(:created_at).limit(10)
topics.each do |topic|
        puts topic.user.username #报错
end

输出 test, 可能你录数据没录好,没对应到 user. mongo 就是不太严格。

因为某条记录的 user_id 是空的

Topic.where(:user_id => nil).to_a

另外,inverse_of 这个参数不必要。

@hhuai @Rei 谢谢两位大哥的指点,就是你们说的,user_id 为空导致 user 没对应到,出现这个问题的原因是我一个大意的疏忽,belong_to :user 是我后来加近 topic model 里的,而之前我无意间录入了一条 topic 的记录,导致那条记录没有 user_id.再次谢过二位🙏

需要 登录 后方可回复, 如果你还没有账号请 注册新账号