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
Found the solution. Issue was with Rails association. Changed code to below and it works now. user model
customer model
Do not use
::
when declaring nested classes/modules. The scope resolution operator does not set the correct module nesting. Take this example: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.