简体   繁体   中英

Convert View block to helper method

I have an Each/do block in my view currently, but I'd prefer to push this code into a helper, as I need to add a few conditional statements in there so I don't want to clutter up my view. Here is the view I have currently that I have been trying to code as a helper method with no luck so far

<% update.voters_who_voted.each do |voter| %>
  <%= link_to profile_path(voter) do %>
    <%= thirty_avatar(voter) %>
  <% end %>
<% end %>

How would this translate into a helper with this name

def find_voters_who_voted(update)
  ...
  ...
end

I've tried this with no luck

def find_voters_who_voted(update)
  update.voters_who_voted.each do |voter|
    link_to profile_path(voter) do
      thirty_avatar(voter)
    end
  end
end

Remember that all you are doing is displaying the return value of this method. It looks like you are expecting it to act as if it's part of the view, but that's not the way helpers work. Something like this would return the equivalent of your original code block

def find_voters_who_voted(update)
  update.voters_who_voted.collect do |voter|
    link_to profile_path(voter) do
      thirty_avatar(voter)
    end
  end.join
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM