[BrainStorm] how to convert a string into an ActiveModel? #414
RomainMazB
started this conversation in
General
Replies: 1 comment
-
I think this is possible. What we need here is We can find the
So, basically we define three entities in Rust |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi!
Thinking about a feature discussed previously, I'm stuck into a problem that I cannot solve and don't even know if it's doable, so I'm opening a brainstorm discussion to solve this problem.
The subject,
how to convert a string into an ActiveModel
is related to polymorphic relationship.What is a polymorphic relationship
For those who are not familiar with this kind of relationship, this relationship is more a way to reduce the amount of tables in the database than a magic relationship.
Say we have a Comment Entity, which is related to both Video Entity and Article Entity.
Instead of having 4 tables:
We could have only one relationship table
comments
where the relationship is store on two columns instead of one:commentable_id
, the id of the related news or videocommentable_type
, the full path of the type of the News or Video ActiveRecord likeblog::Models::News::ActiveEntity
if the comment is related to a News.Because we can't have a foreign key on the comments table, it's recommended to have an index on the two columns to decrease the performance-loss.
Where is the problem?
The problem is that in higher-level language, it's easy to convert a string into a instance of something, example in PHP we could have done:
This is a mess because the string could be anything, but this is true. We generally make sure that the path actually exists and it's a instance of ActivrRecord, but the type system remains stuck and so does the IDE.
Now you understand the problem: is it possible in Rust to get an instance of a struct with only a string containing it's full path identifier?
Because I bet that it's not possible due to its type system, the real question is: how do we tackle this?
One way to go would be that the
RelationDef
of the polymorphic relationship store aHashMap
with an identifier as keys, and the related instance constructor as value so we could do make sure that a corresponding key exists in the HashMap and return back the instance.This is one way but maybe not the better one.
Does anyone have a better idea on how this could be done? Or maybe knows a crate that it implements something similar?
Thanks for your bit of knowledge!
Beta Was this translation helpful? Give feedback.
All reactions