Mongoid - 是否可以嵌入模型嵌入的内容_in?

时间:2012-03-06 13:12:00

标签: ruby-on-rails-3 mongodb mongoid

是否可能有以下类型的关系:

用户:

class User
  include Mongoid::Document
  include Mongoid::Paperclip
  include Mongoid::Timestamps

  store_in :users
  belongs_to :team
  field :full_name,   :type => String
  field :email,       :type => String

  attr_accessible :full_name, 

end

任务:

class Task
  include Mongoid::Document
  include Mongoid::Timestamps

  embedded_in :user
  embeds_one :sender, :class_name => "User"

  field :text,        :type => String
  field :due_time,    :type => DateTime
  field :completed,   :type => Boolean,  :default => false

  attr_accessible :text, :due_time
end

但是当我在rails console中尝试时,我得到了以下内容:

>  u1 = User.where(...).first
>  u2 = User.where(...).first
>  task = Task.new
>  task.user = u1
>  task.sender = u2

NoMethodError: undefined method `first' for #<Task:0x47631bc9>
        from org/jruby/RubyKernel.java:227:in `method_missing'
        from /Users/larry/.rvm/gems/jruby-1.6.7@entercamp/gems/mongoid-2.4.6/lib/mongoid/attributes.rb:166:in `method_missing'
        from /Users/larry/.rvm/gems/jruby-1.6.7@entercamp/gems/mongoid-2.4.6/lib/mongoid/relations/embedded/many.rb:292:in `substitute'
        from org/jruby/RubyProc.java:270:in `call'
        from org/jruby/RubyProc.java:220:in `call'
        from /Users/larry/.rvm/gems/jruby-1.6.7@entercamp/gems/mongoid-2.4.6/lib/mongoid/relations/embedded/atomic.rb:61:in `atomically'
        from org/jruby/RubyProc.java:270:in `call'
        from org/jruby/RubyProc.java:220:in `call'
        from /Users/larry/.rvm/gems/jruby-1.6.7@entercamp/gems/mongoid-2.4.6/lib/mongoid/relations/embedded/atomic.rb:82:in `count_executions'
        from /Users/larry/.rvm/gems/jruby-1.6.7@entercamp/gems/mongoid-2.4.6/lib/mongoid/relations/embedded/atomic.rb:60:in `atomically'
        from /Users/larry/.rvm/gems/jruby-1.6.7@entercamp/gems/mongoid-2.4.6/lib/mongoid/relations/embedded/many.rb:290:in `substitute'
        from org/jruby/RubyKernel.java:1787:in `tap'
        from /Users/larry/.rvm/gems/jruby-1.6.7@entercamp/gems/mongoid-2.4.6/lib/mongoid/relations/embedded/many.rb:283:in `substitute'
        from /Users/larry/.rvm/gems/jruby-1.6.7@entercamp/gems/mongoid-2.4.6/lib/mongoid/relations/accessors.rb:128:in `tasks='
        from org/jruby/RubyProc.java:270:in `call'
        from org/jruby/RubyKernel.java:2080:in `send'

这种定义是不可能的,还是出现了其他问题?

1 个答案:

答案 0 :(得分:2)

听起来您希望在用户内部存储各个任务,并在该任务内部存储发件人用户。

在这种情况下,您想要在rails控制台中测试它的目的是:

>  assignee = User.where(...).first
>  assigner = User.where(...).first
>  task = Task.new
>  task.sender = assigner
>  task.save
>  assignee.task = task
>  assignee.save

右?在这种情况下,我认为你的课程可能看起来像这样:

<强>任务

class Task
  embedded_in :assignee, :class_name => "User"
  embeds_one :assigner, :class_name => "User"
end

用户

class User
  embeds_many :tasks
  embedded_in :task
end