2

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
0

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Got to know Project.pluck(:name), (pluck), @Dario, yes you are right, cant stop loving ruby :)
1

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.

Comments

1

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

1 Comment

Hmm can I ask you "why?" I always wondered to know the answer but can you develop your point please?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.