has_one和mongoid:undefined方法`empty?'对于#<user> </user>

时间:2014-02-20 20:36:18

标签: ruby-on-rails devise mongoid

获取未定义的方法`空?&#39;尝试将当前logged_in用户保存到模型时,我的控制器中出现#error错误。

使用装备和导轨4。

型号:

  class Event

  include Mongoid::Document

  field :name, type: String
  field :description, type: String
  field :date, type: Date

  embeds_many :invitees, cascade_callbacks: true
  embeds_many :participants, cascade_callbacks: true
  embeds_many :comments, cascade_callbacks: true
  embeds_many :options, cascade_callbacks: true

  has_one :owner, :class_name => "User"

  accepts_nested_attributes_for :options, autosave: true, allow_destroy: true
  accepts_nested_attributes_for :participants, autosave: true, allow_destroy: true
  accepts_nested_attributes_for :comments, autosave: true, allow_destroy: true
  accepts_nested_attributes_for :invitees, autosave: true, allow_destroy: true
  accepts_nested_attributes_for :owner, autosave: true, allow_destroy: true

  end

控制器:     ...     def create

    @event = Event.create(event_params)

    if user_signed_in?
      @event.create_owner(current_user)
    end

    respond_to do |format|
      if @event.save
        #TODO: Save users attached to event in user collection
        format.html { redirect_to @event, notice: 'Event was successfully created.' }
        format.json { render action: 'show', status: :created, location: @event }
      else
        format.html { render action: 'new' }
        format.json { render json: @event.errors, status: :unprocessable_entity }
      end
    end
  end
  ....

我做错了什么?

编辑: 这是堆栈跟踪:

  

C:/Rails/Ruby1.9.3/lib/ruby/gems/1.9.1/bundler/gems/mongoid-5b0f031992cb/lib/mongoid/attributes/processing.rb:21:在   process_attributes' C:/Rails/Ruby1.9.3/lib/ruby/gems/1.9.1/bundler/gems/mongoid-5b0f031992cb/lib/mongoid/document.rb:110:in阻止初始化&#39;   C:/Rails/Ruby1.9.3/lib/ruby/gems/1.9.1/bundler/gems/mongoid-5b0f031992cb/lib/mongoid/threaded/lifecycle.rb:84:在   _building' C:/Rails/Ruby1.9.3/lib/ruby/gems/1.9.1/bundler/gems/mongoid-5b0f031992cb/lib/mongoid/document.rb:104:in初始化&#39;设计(3.0.4)lib / devise / models / confirmable.rb:46:in   initialize' C:/Rails/Ruby1.9.3/lib/ruby/gems/1.9.1/bundler/gems/mongoid-5b0f031992cb/lib/mongoid/factory.rb:23:in 新&#39;   C:/Rails/Ruby1.9.3/lib/ruby/gems/1.9.1/bundler/gems/mongoid-5b0f031992cb/lib/mongoid/factory.rb:23:在   build' C:/Rails/Ruby1.9.3/lib/ruby/gems/1.9.1/bundler/gems/mongoid-5b0f031992cb/lib/mongoid/relations/builders.rb:93:in 阻止创作者&#39; app / controllers / events_controller.rb:31:create' actionpack (4.0.0) lib/action_controller/metal/implicit_render.rb:4:in send_action&#39; ...

1 个答案:

答案 0 :(得分:0)

问题是你正在调用函数“空?”在用户记录未定义时。在最简单的情况下,这在rails控制台中失败了:

1.9.3-p194 :001 > User.first.empty?
    User Load (9.3ms)  SELECT `users`.* FROM `users` ORDER BY `users`.`id` ASC LIMIT 1
    NoMethodError: undefined method `empty?' for #<User:0x007fe0375d8c10>

您可以通过在用户模型中删除该功能来解决此问题:

def empty?
end

但最好弄清楚你在哪里打电话并修理它。错误跟踪应该告诉它源自哪个文件和行。