Skip to content

Instantly share code, notes, and snippets.

@pinzonjulian
Last active January 13, 2021 01:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pinzonjulian/75fa58b0791a96d7ecd21480d9a47012 to your computer and use it in GitHub Desktop.
Save pinzonjulian/75fa58b0791a96d7ecd21480d9a47012 to your computer and use it in GitHub Desktop.
# UNEXPECTED BEHAVIOUR
class User < ApplicationRecord
has_many :client_posts,
class_name: Client::Post.name,
foreign_key: :user_id
end
class Client::Post < ApplicationRecord
# Note how the class_name is declared here
belongs_to :owner,
class_name: User.name # This returns just a "User" string
end
class Client::User < ApplicationRecord
# has no relationship to any of the above
end
# Calling reflections on the Client::Post class
Client::Post.reflections['owner']
# as part of the reflection's info, this returns an unwanted @klass name
=> @klass = Client::Post
# I'm expecting this to be just User
# Calling user.posts returns a collection of posts
# Calling client_post.owner returns nil because it's searching for a user in the Client::User table instead of the User table
# Workaround
class User < ApplicationRecord
has_many :client_posts,
class_name: Client::Post.name,
foreign_key: :user_id
end
class Client::Post < ApplicationRecord
# Note that a double colon is used inside the string declaration
belongs_to :owner,
class_name: "::User"
end
class Client::User < ApplicationRecord
# has no relationship to any of the above
end
# Calling reflections on the Client::Post class
Client::Post.reflections['owner']
# as part of the reflection's info, this returns nil @klass name
=> @klass = nil
# I'm expecting this to be just User
# However the instance methods to call the related objects work correctly
# Calling user.posts returns a collection of posts
# Calling client_post.owner returns an instance of User which is what I expect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment