interskh
interskh

Reputation: 2591

Rails named relationship with same class name

I have two classes like this:

class User < ActiveRecord::Base
  has_one :my_user, class_name: 'My:User'
end

class Mynamespace::User < ActiveRecord::Base
  belong_to :user
end

The problem here is that from User i can get my_user object by User.find(1).my_user, but not vice versa:

Mynamespace::User.find(1).user ends up getting me same My:User object.

I have also tried this, but that does not work either.

class Mynamespace::User < ActiveRecord::Base
  belong_to :user_parent, :class_name => 'User', :foreign_key => 'user_id'
end

Any advice? Thank you in advance!

Upvotes: 1

Views: 366

Answers (1)

user229044
user229044

Reputation: 239382

Use ::User to reference the model in the root namespace.

class Mynamespace::User < ActiveRecord::Base
  belong_to :user, class_name: '::User'
end

Upvotes: 1

Related Questions