Reputation: 87
I am new to Ruby on Rails, and I am not confident about my MVC logic.
I am proceeding in this way:
@users = User.all
<%= @users.each ... %>
I was asking myself in I could bypass the controller step and write this in my views : <%= User.all.each ... %>
I'd like to use good practices in my project, is the second way acceptable?
Upvotes: 2
Views: 2700
Reputation: 1124
in real life operations in controller more complexier then User.all.each for example
@cars = Car.scoped
@cars = @cars.includes(:body_type, :brand, :city, :drive, :engine_type, :model, :region, :transmission)
@cars = @cars.select(['`cars`.*','`stats`.recount']).joins('left outer join stats on (cars.model_id = stats.model_id and cars.year = stats.year)')
@cars = @cars.limit(15)
and mode and more other logic
in view you need only to render this object
in my example i use render partial
in view
= render @cars
and in view/_car.html.haml
- for car in @cars
.row-fluid.car
= car.price
= etc
so, if you whant to change view you changing view
if you whant to change behavior of collecting process you changing controller
if you whant to change behavior of object you changing model
the same things with bugs
all in strict order
the order is good and beautiful
Upvotes: 1
Reputation: 14227
so yes it's possible to move everything to view (even database request), but it's not good idea, Ideally you should move it to controller
Upvotes: 0
Reputation: 25757
The idea of interacting with the query interface of ActiveRecord only from within controller actions is maintainability. If you follow the approach you can roughly know what an application is supposed to do by looking at it's controllers. Also, if the logic would become more complex (e.g. you want to add authentication and/or authorization), that behavior would go into the controller.
In contrast, if you look at one of your views, it should be clear how the page looks. If there are calls to model classes all over the place, this is less obvious.
Perhaps, you can think of it like this:
If you want to change a certain aspect of your app, you should only have to touch the respecitve component responsible for the aspect.
Upvotes: 0
Reputation: 2270
Technically, you can, your User model is just a Ruby class and is accessible from your views. However, it is most definitely not a good practice.
Rather than going in lengths to talk about why this shouldn't be done, I'll just link to some articles/documentation for you and advice you to get a good feel for the reasoning behind MVC architecture first, before moving further into Rails:
Upvotes: 0