Search code examples
ruby-on-railspaginationrenderpartial

Rails Partial with variable


UsersController

def index
    @users = User.all.paginate(page: params[:page])   
end

users/index.html.erb

  <% @users.in_groups_of(3, false).each do |users| %>
    <% users.each do |user| %>
      <% unless current_user == user %>
        <div id="follow">
          ????????????
        </div>
      <% end %> 
    <% end %> 
  <% end %>
  <%= will_paginate @users %>

I want to turn the following into a partial, 'users/_follow_form'

<% if current_user.following?(user) %>
  <%= form_for(current_user.active_relationships.find_by(followed_id: user.id),
    html: { method: :delete }, remote: true) do |f| %>
        <%= f.submit "Unfollow", class: "btn btn-primary" %>
    <% end %>
  <% else %>
    <%= form_for(current_user.active_relationships.build, remote: true) do |f| %>
      <div><%= hidden_field_tag :followed_id, user.id %></div>
      <%= f.submit "Follow", class: "btn btn-primary" %>
    <% end %>
  <% end %>
</div>

What code do I need to use to render it?


Solution

  • <div id="follow">
       <%= render partial: "users/follow_form", locals: {passUser: user} %>
    </div>
    

    This will pass your <% users.each do |user| %> user to the partial assigned as passUser. You can get this passUser variable in the users/_follow_form partial like:

    <% if current_user.following?(passUser) %>
    

    Check this for more.