When making a relation like belongs_to :author
I've always used the option :class_name => 'User'
but I never liked it. It isn't semantic, IMO.
So I was thinking about an alias for my User
model. "Well", I thought, "a model is simply a constant, so let's put another name to it.
Then I wrote Author = User
and saved it in app/models/author.rb
.
Looked good, and worked well for all purposes except one. When I tried to use my relation, say post.build_author
I get uninitialized constant Post::Author
.
Why can't ruby find my constant Author
?
Seems like Post
can't reach it, so I tried this:
class Post
def author_class_test
Author
end
end
=> Post.new.author_class_test
=> User(...)
So, I assume Post
can "see" Author
. But not when working with relations, does anybody knows why is that ?
Thanks in advance.
Update.
So, out of curiosity I tried this:
class Post
Author = User
...
end
Then again Post.new.build_author
which again got me uninitialized constant Post::Author
. But at least now I know he's lying to me. :P
The trace ends here: https://github.com/rails/rails/blob/master/activerecord/lib/active_record/inheritance.rb#L142
I'm starting to think it's an edge case which ActiveRecord does not considers.