Tuesday, 20 August 2013

Ruby on Rails: How to have multiple controllers for one table AND multiple models

Ruby on Rails: How to have multiple controllers for one table AND multiple
models

I'm new to Ruby and to Rails. I have played a bit with Sinatra but I think
that Rails is a more complete framework for my project. However, I am
running into trouble with this.
I am working with an fairly substantial existing, and heavily used, mySQL
database and I am trying to build an API for this that will report on
certain features. The features that are needed are, for the most part,
counts of records by certain groupings, then drilling down into details.
For example we have a table - tableA, that contains lots of information
relating to documentation. One piece of information we want to report on
from that is the number of items in a given language. The language code is
stored against each item and based on a get request I would like to return
JSON.
Request: /languages/:code/count/:tablename
There are two variables in that most specific URL - the code we are
counting and the table we are counting from.
I understand that in routes.rb I can set up a mapping:
get '/languages/:code/count/:table', :controller=>'languages',
:action=>'count'
I have a controller - languages_controller.rb with a count method in it.
this then matches to a corresponding view file count.html.erb
In all the tutorials I have read and examples I have followed the main
point seems that 'languages' would be a table in the database and would
therefore be available under the 'magic' Rails approach.
My issue is that it is not a table, rather the results of the call should
be a limited subset of the fields in tableA. Such as languagecode and
count(id).
The description of the language needs to be looked up 'manually' as it is
stored as an internal code that is not in a database anywhere (historic
decision/madness).
The questions: 1. how do I have a model that is only a subset of fields,
plus some that are manually populated - languagecode, isocode,
description, count 2. Am I right in thinking that once I have the model
defined as such as I could use ActiveRecord to get data from the database
and then in the controller add the extra information in? 3. Can I change
table in the model based on the parameter sent in the URL?
Essentially, I am at a loss at the moment on what to do with this. I have
the routes defined, the view templates in place and the controller there
and ready to go. The database component - getting some data from a
pre-existing table seems mysterious to me.
Any help is greatly appreciated, it seems that the framework is currently
getting in my way and I know that I can't be the only one trying this sort
of thing so if you have any advice please share.

No comments:

Post a Comment