开发者

Trying to view a referenced document: illegal ObjectId format

Trying to view an attribute to a referenced document. The issue is in the task's index file. When I try to display the tag associated with the task I get the following error:

BSON::InvalidObjectId in Tasks#index

The error is on '<%= task.tag.title %>' line in the ind开发者_JS百科ex.html.erb file.

user.rb

class User
  include Mongoid::Document
  field :name
  validates_presence_of :name
  validates_uniqueness_of :name, :email, :case_sensitive => false

  attr_accessible :name, :email, :password, :password_confirmation

  embeds_many :tags
  embeds_many :tasks

  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
end

tag.rb

class Tag
  include Mongoid::Document
  field :title
  embedded_in :user, :inverse_of => :tags
  references_many :tasks
end

task.rb

class Tag
  include Mongoid::Document
  field :title
  embedded_in :user, :inverse_of => :tags
  references_many :tasks
end

index.html.erb

<% @tasks.each do |task| %>
  <tr>
    <td><%= task.name %></td>
    <td><%= task.tag.title %></td>
  </tr>
<% end %>

Thanks,


I ran into a similar problem myself recently (2.0.0.rc.7). In my case a Rails collection_select was ending up writing an empty string value into a reference field (e.g. tag_id). When mongoid attempted to reload the document and my code referenced the association it failed to convert empty string to a valid BSON object ID.

It looks like it is a known issue and has been fixed but hasn't made it into a new build just yet.

https://github.com/mongoid/mongoid/issues/closed#issue/651

https://github.com/mongoid/mongoid/issues/closed#issue/690

In the meantime I ended up working around the problem by writing a before_save event handler to convert the empty string values to nil. e.g.

  before_save :before_save
  def before_save
    self.tag_id = nil if self.tag_id == ''
  end

Its just a workaround and should be unecessary with 2.0.0.rc.8. It will only stop invalid object references being saved, it won't clean up any data that is already in the database.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜