Evando
Evando

Reputation: 61

Having multiple database tables for one controller in Rails

I have a project using Rails where I would like to have multiple SQLite tables associated with one controller. I've looked around and haven't seen anything about this. Is this possible? I do have multiple controllers now, but I'd like to try and consolidate them.

Upvotes: 1

Views: 1395

Answers (1)

Klaus
Klaus

Reputation: 1771

Ruby on Rails uses the MVC paradigm. That means, very simple explained, the models (M) are responsible for data storing and retrieving, the views (V) are for displaying and the controllers (C) take and send requests.

A simple example: A user sends the request for displaying a page. The controller takes this request. If there are data from a database needed to display on the page, the controller asks the related model. The model takes this data from database, send it to the controller which then send it to the view.

If, in your example, the data are stored in different database tables, the controller is responsible to ask their related models.

For example, you have a database table called projects and another one called tasks and a third called users, than you must have three models: Project model, Task model and User model. Each model is responsible for its database table.

Maybe you have a view (it will generate a html-page) where you want to display data from all three tables. Let's call it show.html.

Following the Rails convention you have an corresponding action 'show' in your controller. You have to tell this action, what kind of data you need for the view.

class YourAwesomeController < ApplicationController

  def show
    @project = Project.find(1)
    @task    = Task.find(21)
    @user    = User.find(42)
  end
  ... # some other actions

end

That means, that your action 'show' in your controller 'YourAwesomeController' asks the model Project to fetch the row from the 'projects' table with the id = 1, then the Taks model to fetch the row from the 'tasks' table with the id = 21 and finally it wants the User model to fetch the row with the id = 42 from table 'users'.

Notice: The controller doesn't know where the needed data are stored. He only knows (via your code) the models (it's conceivable thta the user's data are stored in an external webservice. If so, the model knows this and the controller doesn't mind, because he is just asking the model to send him the data he needs)

In your 'show.html.erb' you can use now the instance variables @project, @task and @user to show the data.

Ruby on Rails shows its full power and magic, if you follow the conventions. However, even if you are not using Rails, it's always recommended to follow the MVC paradigm.

Upvotes: 3

Related Questions