Forum: Ruby on Rails access model from controller

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Yannick M. (Guest)
on 2006-06-01 13:21
(Received via mailing list)
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
Alder G. (Guest)
on 2006-06-01 14:28
(Received via mailing list)
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.
Yannick M. (Guest)
on 2006-06-01 15:49
(Received via mailing list)
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
anonymous coward (Guest)
on 2006-06-01 15:53
...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
Alder G. (Guest)
on 2006-06-01 16:41
(Received via mailing list)
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.
David F. (Guest)
on 2006-06-01 16:53
(Received via mailing list)
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
Yannick M. (Guest)
on 2006-06-01 17:00
(Received via mailing list)
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
Alder G. (Guest)
on 2006-06-01 17:12
(Received via mailing list)
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.

2. 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.
Yannick M. (Guest)
on 2006-06-01 17:25
(Received via mailing list)
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.

> 2. 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  ;-) ).

 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
Alder G. (Guest)
on 2006-06-01 18:52
(Received via mailing list)
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  ;-) ).

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!
This topic is locked and can not be replied to.