Sirch
Sirch

Reputation: 417

Rails - Is it better to use class methods in controller or Views

In my rails model, i define a class and a method to return me an array of Project names. Now my question is, should I, is it correct to use the Project.names array in my view, or should I generate an array in the controller, and pass with an instance variable.

class Project < ActiveRecord::Base

...snip...

  def self.names
    Project.select(:name).map {|x| x.name }
  end

end

Upvotes: 2

Views: 1716

Answers (3)

Dario Barrionuevo
Dario Barrionuevo

Reputation: 3277

I'll definitely stick to fill the instance variable in the controller. BTW, a word about your code:

Project.select(:name).map {|x| x.name }

Can be refactored to:

Project.select(:name).map(&:name)

An this, can be refactored to:

Project.pluck(:name)

Love Ruby.

Upvotes: 2

Laas
Laas

Reputation: 6078

From practical perspective, it is always a hard decision where to draw the line between view layer and controller logic. It could be questionable to fill your controller with the likes of:

# controller
@project_names = Project.names

# view
<%= @project_names.join(", ") %>

Only to use the @procject_names in the view.

But keeping that code out from views would give you later the opportunity to do this without changing the view:

# Controller is updated
@project_names = Project.names

# Show only matching projects
if params[:search]
  @project_names = @project_names.select{|n| n =~ /#{params[:search]}/}
end


# view - still the same
<%= @project_names.join(", ") %>

Also, take look at the Draper gem which builds upon the Decorator pattern and ViewModel of the MVVM pattern.

With Draper, you can keep even your controllers cleaner and have multiple decorators for same object depending on the need (e.g one for web, other for mailer) while still using same view code to render output.

Common thing to place in the Decorator is localized dates which depend on logged in user, therefore don't fit into view, but would clutter the controller with view-layer logic.

Upvotes: 1

John
John

Reputation: 3296

It's generally considered best practice to separate the pulling of data and the display of data appropriately, where the view is responsible for only displaying that data. I'd definitely say it would be a better idea to generate the array in your controller and pass it in to your view.

MVC is a quite a large topic - for more information check out the Rails Guides: http://guides.rubyonrails.org/getting_started.html

Upvotes: 1

Related Questions