Posterous theme by Cory Watilo

Filed under: mongoid

Tip on mongoid many to many relationship failing on save

So you're happily hacking your way with mongoid and you add some many to many relationship between the models. And it hits you as it hit me with a nasty error that does not really help to understand what you did wrong.

All I did was added relationships to two of my models:

 class Site
    references_many :users, :stored_as => :array, :inverse_of => :sites
 end

class User
    references_many :sites, :stored_as => :array, :inverse_of => :users
 end

On the next save I got this error that got me really confused:

Mongo::OperationFailure (invalid query):
app/controllers/admin/sites_controller.rb:46:in `create'
 app/controllers/admin/sites_controller.rb:44:in `create'

# those lines were
@site = Site.new(params[:site])
@site.users << current_user #44
respond_to do |format|
if @site.save #46

The solution is to delete all your existing records, because they had no relationships on them and will fail each and every time when you try to do that. It's good that I was just scaffolding my app and had no real data in there.