0
votes

I'm very new to coding. I'm trying to find a solution on how I can render multiple partials in the same DIV on separate link click.

So far I can render one partial in the div(partial 1), but I'm stuck on how to render other partials when other links are clicked.

This is my code so far

in views/layouts/_sidebar.html.erbI have

   <li>
        <%= link_to user_path(current_user), :remote => true do %>
           <i class="glyphicon glyphicon-home"></i> Partial1
        <% end %>

   </li>
    <li>
        <%= link_to user_path(current_user), :remote => true do %>
           <i class="glyphicon glyphicon-flash"></i> Partial2                
        <% end %>
    </li>  

In the users_controller.rbI have

class UsersController < ApplicationController
  before_action :authenticate_user!

   def show
      @user = User.find(params[:id])

      @user_partial1 = @user.1partials
      @user_partial2 = @user.2partials

       respond_to do |format|
        format.html { @user_partial1 }
        format.js { render :show }
       end
    end   
end

In the users/show.html.erbI have

<div id="usercontent"></div> were the partials should render.

in the view/users/show.js.erb there is this code

$("#usercontent").html("<%=escape_javascript(render :partial=>"shared/partial1")%>");

This code works fine to render only one partial in one div but I can't figure out how to render the other partials in the #usercontentdiv when associated link is clicked.

Can someone please help me?

2
you can use @user_partial1.each do |partial| ..... in your file view/users/show.js.erb.Dapeng114

2 Answers

1
votes

You can pass a parameter along with your link_ to

 <li>
    <%= link_to user_path(current_user,partial: '1'), :remote => true do %>
       <i class="glyphicon glyphicon-home"></i> Partial1
    <% end %>

    <li>
    <%= link_to user_path(current_user,partial: '2'), :remote => true do %>
       <i class="glyphicon glyphicon-flash"></i> Partial2                
    <% end %>
</li>  

In your controller you can get the value of partial to render:

@partial_to_render = params[:partial]

And in view/users/show.js.erb

$("#usercontent").html("<%=escape_javascript(render :partial=>"shared/partial" + @partial_to_render)%>");

If you need to append the content to the existing html in #usercontent div use Jquery append instead of $("#usercontent").html().

0
votes

I have the same problem. I followed the approach of Kumar Abhinav. The only additional thing you need is to specify the partial in the routes. Such as:

get "/show/:partial", to:"users#show"

Now you can trigger multiple partial.