Last active
January 13, 2021 01:03
-
-
Save pinzonjulian/75fa58b0791a96d7ecd21480d9a47012 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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