Reputation: 2967
Given a column name in string format (e.g. "hamburger_id" or "foo_bar_id"), is there a standard way of getting to a class (or class name). In this case, Hamburger or FooBar?
The only way I could think of was this:
column_name[0, column_name.length - 3].camelize.constantize
I can assume (or stipulate) that the variable column_name always contains a string with "_id" at the end and that a corresponding class always exists.
If some one finds it relevant or is curious, I can elaborate on the "why", but I didn't want to clutter up the question with such details.
Upvotes: 0
Views: 210
Reputation: 9700
You could do the following (assuming the traditional Rails example of a Post model that has_many Comment models):
Model.reflect_on_all_associations.select{|a| a.foreign_key == 'column_name'}.first.class_name
This has the advantage that if your class names and foreign keys don't line up, it will still give the correct class name. For instance, if your foreign key is owner_id
but the associated model is actually named User
, this will return "User"
instead of "Owner"
.
This still feels like a bit of a hack, but that's because it's not very Rails-like to get this information based on a column name - Normally you'd interact with the association directly (using reflect_on_association(:foos)
).
Upvotes: 2