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.
1 Answer 1
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.
-
\$\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– Greg Burghardt2015年04月21日 18:43:56 +00:00Commented Apr 21, 2015 at 18:43
@products = Product.all
. That's using the modelProduct
. \$\endgroup\$Product
model may be empty but it's based onActiveRecord::Base
which certainly isn't empty. Hence why there's anall
method you can call. \$\endgroup\$