2 / 2
May 2024

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 obvious here?

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'