Why Avoid Using Instance Variables for Views in Ruby on Rails

rubyruby-on-rails

Why do I hear that it is not good to share instance variables between controllers and views. I kind of like it because I can see immediately via the @ that something is coming from the controller. I see a nice way to use helpers in controllers here: http://www.stephencelis.com/2008/09/06/rails-controllers-views-and-variables.html. But I am using cancan for that portion.

Best Answer

The idea was put up in rails best practices: Replace instance variable with local variable

Basically if you don't use many partials or have a single plain view for each controller method just using the instance variables in the view wouldn't really cause any trouble.

Nevertheless, if you use many partials and therefore have many instance variables declared in your controller..., it might be less confusing if you use the alternative of passing the controller (instance)-variable to the partials explicitly. That way - while working in the partial VIEW - you have one explicit reference to the variable/object you want to work with that is not shared with 'all' partials that are included in the creation of the page.

After all, you can handle this just as you like to handle it, noone will tell you to do it otherwise. My personal view, however, is that I like the idea of having explicitly references in my partials/views that can not be confused with other variables.

Related Topic