1
\$\begingroup\$

I don't think I am using the MVC concept in Ruby on Rails properly. Model accesses db, controller works on logic and view displays information/data. But in my code, my Model code is empty. Can anyone please help in analyzing on how I can use MVC correctly?

Model:

class Product < ActiveRecord::Base
end

Controller:

class AdminController < ApplicationController

    def index
        @products = Products.all
    end

end

View:

<h3 class="sub-header">Product</h3>
<table border='1' class="table table-striped" width="200">
    <tr class="success">
        <th>ID</th>
        <th>url</th>
        <th>url id</th>
        <th>price id</th>
    </tr>

<% @products.each do |user| %>
    <tr>
        <td><%= user.id %></td>
        <td><%= user.url %></td>
        <td><%= user.url_id %></td>
        <td><%= user.price_id %></td>
    </tr>
<% end %>
</table>

Here I am displaying values from my database table 'Product' in an HTML table. Although it does what I want, I don't think I am doing it right.

\$\endgroup\$
  • 1
    \$\begingroup\$ @products = Product.all. That's using the model Product. \$\endgroup\$ – tokland Apr 13 '15 at 17:26
  • 1
    \$\begingroup\$ What tokland said. Your Product model may be empty but it's based on ActiveRecord::Base which certainly isn't empty. Hence why there's an all method you can call. \$\endgroup\$ – Flambino Apr 13 '15 at 21:49
  • \$\begingroup\$ Am I usin Mvc properly though \$\endgroup\$ – fscore Apr 14 '15 at 10:51
3
\$\begingroup\$

This is perfectly correct use of MVC. It's also, extremely simplistic so you're seeing a nearly empty model and controller.

I can only assume that it 'feels' wrong for that reason, and in this example your only real work is done in the view.

In the view you can and should have things like loops and if statements as long as those blocks are there to assist the rendering of the page.

The controller should hold your core logic and get everything ready for the view. You're doing that here, and for the sake of example lets say you wanted to also get a Product list grouped by the number of times it had been ordered. You would write your active record selection and set a variable that can use in your view to show a list of product by popularity in another page element.

Your model will hold things like validations, relationships and scopes. Each is responsible for only one 'table'. Expanding on that your controller might pull data from multiple models and prepare it for the view.

\$\endgroup\$
  • \$\begingroup\$ The controller shouldn't have core logic. The core logic, or business logic, should be in the model. The controller should do little more than react to what the model layer does. \$\endgroup\$ – Greg Burghardt Apr 21 '15 at 18:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.