h9_nier
h9_nier

Reputation: 1

Could I not use instance variables?

I'm new to Rails and I have a question. Everyone says the preferred way of iterating through a table is to capture the data in an instance variable via a Controller, then iterate in the corresponding View.

What if I just did

<% Course.all.each do |course| %>
  <!-- displays list of courses -->
<% end %>

I know using instance variables is the preferred way, but is there any reason?

Upvotes: 0

Views: 57

Answers (2)

Tom Lord
Tom Lord

Reputation: 28305

Could I not use instance variables?

Yes. The code, as you've written it, works.

Using instance variables is the preferred way, but is there any reason?

It's really just an agreed design pattern to do avoid making database queries directly in the view.

A principle of MVC frameworks is to have the controller prepare all data for the view, rather than the view directly fetching data at arbitrary points. In the long term, you'll find the latter approach can become messy, un-performant and difficult to maintain.

For example, you might start making the same query multiple times, or run into N+1 problems, or struggle to test the implementation at all (because if logic is all inside the view, the only way to test might be via very complex+expensive feature tests, instead of quick and easy unit tests!) - which can make the implementation fragile and error prone.

But rules are made to be broken, and you can write code like this in rails; just take a word of warning from the past experience of developers who invented MVC frameworks in the first place: This is generally a design pattern to be avoided.

Upvotes: 4

Rystraum
Rystraum

Reputation: 2025

You certainly CAN do this, but it does not mean it is a good idea.

Rails operates as an MVC framework which separates models, views & controllers, which in turn is really an application of the "Separation of Concerns" design principle.

By adding controller responsibilities (fetching data) into view responsibilities (displaying data & interacting with the users), you're making it more difficult for the view code to be reused.

  • What if you only want to display a subset of courses but not all of them, but using the same format?
  • What if you want to display a different set of courses depending on who the user is at the moment?
  • What if you want to paginate the course list because you've got 1,000 courses already?

And so on.

This is really hard to appreciate when you are just starting out but getting into the habit as early as possible will save yourself from unlearning it later down the line.

At the end of the day, these are just conventions, and there is a time and place wherein you can break conventions but just be aware that all these "rule-breaking" might eventually come back and haunt you. That's what we call "technical debt" and as with any kind of debt, the longer you keep it, the harder it is to pay it off.

Upvotes: 1

Related Questions