skip to Main Content

I am using mongodb for first time. I have below models

class Legacy::User
  include Mongoid::Document

  has_many :customers
  field :username, type: String
end

class Legacy::Customer
  include Mongoid::Document

  belongs_to :user
  field :user_id, type: String
end

When I run below query it doesn’t return customer record.

Legacy::User.last.customers

Queries from console

{"find"=>"legacy_users", "filter"=>{}, "limit"=>1, "skip"=>0, "sort"=>{"_id"=>-1}, "$db"=>"bo_development", "lsid"=>{"id"=><BSON::Binary:0x21780 type=uuid data=0xb35d9aef1441401b...>}}

{"find"=>"legacy_customers", "filter"=>{"_id"=>"zx54QQx4gPbJvQ3rm"}, "$db"=>"bo_development", "lsid"=>{"id"=><BSON::Binary:0x21780 type=uuid data=0xb35d9aef1441401b...>}}

Look at the second query, why doesn’t it use user_id in filter? Am I missing something here?

2

Answers


  1. Chosen as BEST ANSWER

    Found the solution. Issue was with Rails association. Changed code to below and it works now. user model

    has_many :legacy_customers, class_name: 'Legacy::Customer', foreign_key: 'user_id'
    

    customer model

    belongs_to :legacy_user, class_name: 'Legacy::User', foreign_key: 'user_id'
    

  2. Do not use :: when declaring nested classes/modules. The scope resolution operator does not set the correct module nesting. Take this example:

    module Legacy; end
    
    class Legacy::Customer
    end
    
    class Legacy::User
      puts Module.nesting
      Customer # uninitialized constant Customer
    end
    

    It will give you [Legacy::User] and not [Legacy::User, Legacy].

    If you instead declare the namespace correctly by reopening the module it will actually resolve other constants in the same module nesting properly.

    module Legacy
      class User
        include Mongoid::Document
        has_many :customers # will resolve to Legacy::Customer
        field :username, type: String
      end
    end
    
    module Legacy
      class Customer
        include Mongoid::Document
        belongs_to :user
        # You do not need to define the user_id field 
      end
    end
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search