Ashish Agrawal
Ashish Agrawal

Reputation: 381

ActiveRecord query in views and helpers in Rails

I have the following associations defined in my application:

class Person
  belongs_to :type
end

class Type
  has_many :people
end

Now, in the new and edit form for person, I need to give a dropdown that will show all the types which will come from the Type model.

Now there are two approach to do the same:

1. make an instance variable in controller for types and access that in the form view.

class PeopleController 

  before_action :get_types, only: [:new, :create, :edit, :update]

  def new  
  end

  def create
  end

  def edit
  end

  def update
  end

  private

  def get_types
    @types = Type.all
  end

end

person/_form.html.erb

...
<%= f.select :type_id, @types.collect{ |type| [type.name, type.id]} %>
...

2. Making a database query in the person_helper

person_helper.rb

module PersonHelper
  def get_types
    Type.all
  end
end

person/_form.html.erb

...
<%= f.select :type_id, get_types.collect{ |type| [type.name, type.id]} %>
...


So, I want to know which is the better approach and why.

Note: As per MVC paradigm, controller will provide the necessary data to the views. Neither I am not able to find any difference in the query execution in both the cases nor, I am able to find any good explanation regarding the same apart from the MVC part.

Upvotes: 0

Views: 1311

Answers (1)

Juliana Davila
Juliana Davila

Reputation: 90

The idea with the helper is reuse functionalities for example formatting something or extract complicated logic.

So, if that query is something that you will need in many cases, would be a good idea have it in the helper, there is not really an difference in the query execution, is more about use and have a code more clean.

Upvotes: 2

Related Questions