Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

model name to controller name

How can I get the controller name out of the object if I don't know what the object is?

I am trying to do:

object.class.tableize

but Rails says:

undefined method `tableize' for #<Class:0xb6f8ee20>

I tried adding demodulize with same result.

thanks

like image 809
Pavel K. Avatar asked Oct 27 '09 15:10

Pavel K.


People also ask

What's the difference between model names and controller names?

Fundamentally, the model “knows stuff”. It holds, the business logic of a piece of data. On the other hand, the controller, “does stuff”.

Does every model need a controller?

Do I need a controller for each model? No, not necessarily. However, having one controller per RESTful resource is a convention for a reason, and you should carefully analyze why that convention isn't meeting your needs before doing something completely different.

What is a controller in Ruby?

A controller is a Ruby class which inherits from ApplicationController and has methods just like any other class.


2 Answers

object.class.to_s.tableize
like image 52
bensie Avatar answered Oct 21 '22 01:10

bensie


For semantic reasons, you might want to do:

object.class.name #=> 'FooBar'

You can also use tableize with this sequence, like so:

object.class.name.tableize #=> 'foo_bars'

I prefer it that way due to readability.

As well, note that tableize also does pluralization. If unwanted use underscore.

Hope it helps anyone, even if it's an old thread :)

like image 26
Gabriel Osorio Avatar answered Oct 21 '22 02:10

Gabriel Osorio