Reputation: 381
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]} %>
...
Upvotes: 0
Views: 1311
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