Reputation: 2849
I am working on a app where you can add task etc. I know this is kind of weird but I just like to see how others would implement this. How would you change the following code into a helper method and use it?
The original code
<h2>My Tasks</h2>
<% task = @work.tasks %>
<% if task.empty? %>
<%= link_to 'Create a new task', new_task_path %>
<% else %>
<%= render :partial => 'notes/note', :locals => {:note => @note} %>
<% end %>
My way of doing a helper method
def task_check
task = @work.tasks
if task.empty?
link_to 'Create a new task', new_task_path
else
render :partial => 'notes/note', :locals => {:note => @note}
end
end
In my view
<%= @work.task_check %>
Upvotes: 1
Views: 196
Reputation: 8094
Personally, I wouldn't extract this out at all, this is view logic and it belongs in the views. It definitely doesn't belong in a model, but it could arguably be extracted into a helper. I'd change it slightly:
<h2>My Tasks</h2>
<% if @work.tasks.blank? %>
<%= link_to 'Create a new task', new_task_path %>
<% else %>
<%= render :partial => 'notes/note', :locals => {:note => @note} %>
<% end %>
Calling blank?
instead of empty?
will work even if @work.tasks
is nil
.
Upvotes: 2
Reputation: 11710
You can't define a helper in the model. It won't have access to render
, link_to
or any other controller or view methods. So just define your method almost exactly as is in a file in your helpers
directory, maybe application_helpers.rb
or work_helpers.rb
:
def task_check(work, note)
task = work.tasks
if task.empty?
link_to 'Create a new task', new_task_path
else
render :partial => 'notes/note', :locals => {:note => note}
end
end
And then call it in your view like so:
<%= task_check(work, note) %>
Upvotes: 1