Search code examples
ruby-on-railsdevisemongoid

Mongoid::Errors::MixedRelations: Mongoid + Devise


I have a Model User from Devise with that relations:

user.rb

# Relationships  
references_many :houses, :dependent => :delete

Now I have a Model House created with scaffold:

house.rb

# Relationships
referenced_in :user, :inverse_of => :houses 
embeds_many :deals

Now I have a Model Deal with this relations:

embedded_in :house, :inverse_of => :deals

In my routes.rb I have:

resources :houses do
  resources :deals
end

When I try get the user that make the deal in console:

ruby-1.9.2-p180 :009 > User.first.deals.first

I get the next error:

Mongoid::Errors::MixedRelations: Referencing a(n) Deal document from the User document via a relational association is not allowed since the Deal is embedded.

Solution

  • With the information you provided, an user is not directly related to a deal.

    It seems that you tried to do :

    class User
      [...]
      references_many :houses, :dependent => :delete
      references_many :deals
    end
    
    class Deal
      [...]
      embedded_in :house
      referenced_in :user
    end
    

    As your Deals are embedded into Houses, you can't access them directly from Users through a relation. It is a known limitation of Mongoid.

    You can use :

    @houses_that_match = House.where("deals.user_id" => @user.id)
    @deals = []
    @houses_that_match.each do |house|
      @deals += house.deals.select { |deal| deal.user == @user }
    end