Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get model class from symbol

I'm implementing a method, that will be used in many places of a project.

def do association

end

"association" is a symbol, like :articles, :tags, :users etc.

When the association is :articles, I need to work with the Article model.

When the association is :users, I need to work with the User model.

Etc.

I know, that I can write a helper method, that returns model class, depending on the provided symbol. But is there a ready to use method for that?

like image 666
AntonAL Avatar asked Mar 15 '11 18:03

AntonAL


2 Answers

Rails provides a method called classify on the String class for such purpose.

:users.to_s.classify.constantize
#User

:line_items.to_s.classify.constantize
#LineItem

Edit:

If you are trying to retrieve the class associated with an association, use this approach:

Author.reflect_on_association(:books).klass
# => Book

This will address the scenario where the association name doesn't match the class name.

E.g:

class Order
  has_many :line_items
  has_many :active_line_items, :class_name => "LineItem", 
             :conditions => {:deleted => false}
end

In the example above, :active_line_items will result in ActiveLineItem and our original code will throw error.

Read more about this here.

like image 193
Harish Shetty Avatar answered Nov 01 '22 14:11

Harish Shetty


This will work

(:users.to_s.singularize.capitalize.constantize).find :all, :conditions => ["name = ?", "john"]

And with your example

association.to_s.singularize.capitalize.constantize
like image 21
Adrian Serafin Avatar answered Nov 01 '22 14:11

Adrian Serafin