Access model from controller


#1

Hello,

Rather new to RoR, so I’m not sure about the terminology and such :-/ .

My question is: how could I know the model which is associated to a
controller?

For example:

  • controller class is TestController, which is a subclass of
    ApplicationController
  • associated model class is Test

How could I write some code in a method of ApplicationController to
dermine the current associated model?

So, if I have a “foo” method in ApplicationController (and no such
method in TestController), when I try to go to /test/foo,
ApplicationController::foo is executed. In this method, I would like to,
say, list all Test objects (but it could be another model if called from
another subclass). How could I know that the current model is Test?

Thank you,

Yannick M. http://www.inma.ucl.ac.be/~majoros
Informaticien UCL/INMA-MEMA
4, avenue G. Lemaître
B-1348 Louvain-la-Neuve
Belgium
Tel: +32-10-47.80.10
Fax: +32-10-47.21.80
Si vous avez des problèmes pour afficher ce message (accents qui ne
passent pas, signature électronique, …) votre système de mail n’est
pas conforme aux standards modernes, voir
http://www.inma.ucl.ac.be/~majoros/email.html
#JAPH : http://www.inma.ucl.ac.be/~majoros/japh.txt


#2

On 6/1/06, Yannick M. removed_email_address@domain.invalid wrote:

Hello,

Rather new to RoR, so I’m not sure about the terminology and such :-/ .

My question is: how could I know the model which is associated to a
controller?

Models are not associated to Controllers. A Controller may use several
Models, or none at all.

Models are basically data objects. Controllers control the logic of
your program. You may think of them as objects containing the
functionality (methods) your program embodies. Any such method may
require several data objects, or none.

I recommend you read some simple examples of Rails programs, e.g. any
tutorial demonstrating a simple application like a TODO list.


#3

Alder G. wrote:

Models are basically data objects. Controllers control the logic of
your program. You may think of them as objects containing the
functionality (methods) your program embodies. Any such method may
require several data objects, or none.

I recommend you read some simple examples of Rails programs, e.g. any
tutorial demonstrating a simple application like a TODO list.
Hello,

Thank you for this answer. Actually, I think I understand this, but…
I would like to write some generic methods to, for example, show data
coming from a specific record in a table. I made a generic “show” method
in the ApplicationController class, and it works quite well… but I
need to give it the name of the data I’m “talking about”. For example,
here is how I do it now:

in TestController.rb:

class TestController < ApplicationController
def custominit
@model = Test
end
end

and in application.rb:
class ApplicationController < ActionController::Base
def initialize
@model = Default
@obj_name = self.controller_name
custominit
end
def list
@obj_pages, @objs = paginate @obj_name, :per_page => @recs_per_page
render ‘list’
end
def show
@obj = @model.find(params[:id])
render ‘show’
end
end

Isn’t it possible to get rid of this “custominit” method? Otherwise,
above code seems to be perfect for what I need…

Best regards,

Yannick M. http://www.inma.ucl.ac.be/~majoros
Informaticien UCL/INMA-MEMA
4, avenue G. Lemaître
B-1348 Louvain-la-Neuve
Belgium
Tel: +32-10-47.80.10
Fax: +32-10-47.21.80
Si vous avez des problèmes pour afficher ce message (accents qui ne
passent pas, signature électronique, …) votre système de mail n’est
pas conforme aux standards modernes, voir
http://www.inma.ucl.ac.be/~majoros/email.html
#JAPH : http://www.inma.ucl.ac.be/~majoros/japh.txt


#4

…sorry for barging in on a disscusion i won’t be part of, but for
Alder, i just wanted to comment that in spite of the fact that you
raised about my email(which from my side is apparentely ok, getting
emails etc)i also have an accout at removed_email_address@domain.invalid which you can
also pop an email in that direction.
'ted be nice to get one(at either one of the emails).
good afternoon or whatever, (and happy weeks[:shavooot?])

shai


#5

Try this:

@model = controller_name.camelcase.constantize

You’ll need to do some extra work if your models are namespaced (e.g.
Test::AnotherModel) but this should suffice for most cases.

Cheers!

-DF


#6

On 6/1/06, anonymous coward removed_email_address@domain.invalid wrote:


Posted via http://www.ruby-forum.com/.


Rails mailing list
removed_email_address@domain.invalid
http://lists.rubyonrails.org/mailman/listinfo/rails

OK Shai, I’ll reply to your Yahoo box.


#7

David F. wrote:

Try this:

@model = controller_name.camelcase.constantize

You’ll need to do some extra work if your models are namespaced (e.g.
Test::AnotherModel) but this should suffice for most cases.

Cheers!

Thank you very much, this is exactly what I needed!

Best regards,

Yannick M. http://www.inma.ucl.ac.be/~majoros
Informaticien UCL/INMA-MEMA
4, avenue G. Lemaître
B-1348 Louvain-la-Neuve
Belgium
Tel: +32-10-47.80.10
Fax: +32-10-47.21.80
Si vous avez des problèmes pour afficher ce message (accents qui ne
passent pas, signature électronique, …) votre système de mail n’est
pas conforme aux standards modernes, voir
http://www.inma.ucl.ac.be/~majoros/email.html
#JAPH : http://www.inma.ucl.ac.be/~majoros/japh.txt


#8

On 6/1/06, Yannick M. removed_email_address@domain.invalid wrote:

def custominit
end
Isn’t it possible to get rid of this “custominit” method? Otherwise,
above code seems to be perfect for what I need…

The basic Rails approach is that FooController is not related by
default to model Foo, or indeed to any other model. So you would need
to have custominit or something like it in your code to artificially
create such assoication.

That said, I have two suggestions you might want to consider:

  1. You are in fact creating a class of Controllers - let’s call them
    ModelAssociatedControllers - the behaviour of which is significantly
    different than the normal behavior of Rails controllers. It is
    therefore likely you’d want to add at some point controllers which
    aren’t ModelAssociated. So I’d recommend against making every
    controller in your application ModelAssociated by default, which is
    what you get by putting all the logic in ApplicationController.

Instead, create an abstact base-class ModelAssociatedController, and
have all the ModelAssociatedControllers inherit from it instead of
ApplicationController. For better organization you should even
consider create a dedicated ModelAssociated controller namespace, and
have the abstract baseclass as ModelAssociated::BaseController, which
all contollers inside ModelAssociated inherit. It’s a very neat and
useful pattern.

  1. Leverage the dynamic nature of Ruby to deduce by introspection -
    instead of hard-coding manually - the name of the Model that is
    supposed to be associated. This is consistent with Rails’ preference
    for configuration by convention. Instead of defining and calling
    custominit use:

Object.const_get(controller_name.capitalize)

It will automatically deduce the model name from the controller, i.e.
return a reference to model class Foo if called within FooController.


#9

Alder G. wrote:

therefore likely you’d want to add at some point controllers which
useful pattern.

This seems indeed like a good idea. I don’t know if I need to implement
it now, but that is surely what I’ll do if I ever need controllers which
do not behave this way in my application.

  1. Leverage the dynamic nature of Ruby to deduce by introspection -
    instead of hard-coding manually - the name of the Model that is
    supposed to be associated. This is consistent with Rails’ preference
    for configuration by convention. Instead of defining and calling
    custominit use:

Object.const_get(controller_name.capitalize)

It will automatically deduce the model name from the controller, i.e.
return a reference to model class Foo if called within FooController.

Thank you, it seems to work. I did it with David F.'s suggestion
( @model = controller_name.camelcase.constantize ), but I like this one
more (for rather cosmetic reasons :wink: ).

Best regards,

Yannick M. http://www.inma.ucl.ac.be/~majoros
Informaticien UCL/INMA-MEMA
4, avenue G. Lemaître
B-1348 Louvain-la-Neuve
Belgium
Tel: +32-10-47.80.10
Fax: +32-10-47.21.80
Si vous avez des problèmes pour afficher ce message (accents qui ne
passent pas, signature électronique, …) votre système de mail n’est
pas conforme aux standards modernes, voir
http://www.inma.ucl.ac.be/~majoros/email.html
#JAPH : http://www.inma.ucl.ac.be/~majoros/japh.txt


#10

On 6/1/06, Yannick M. removed_email_address@domain.invalid wrote:

Alder G. wrote:


Object.const_get(controller_name.capitalize)

Thank you, it seems to work. I did it with David F.'s suggestion
( @model = controller_name.camelcase.constantize ), but I like this one
more (for rather cosmetic reasons :wink: ).

Actually, David’s code avoids a bug in mine; if your controller_name
is composed of more than a single word - like ‘hello_world’ -
#capitalize would inflect it to “Hello_world”. Assuming you want
“HelloWorld”, use #camelcase, so my corrected suggestion is:

Object.const_get(controller_name.camelcase)

Tel: +32-10-47.80.10
Rails mailing list
removed_email_address@domain.invalid
http://lists.rubyonrails.org/mailman/listinfo/rails

Enjoy Rails!