Prometheus
Prometheus

Reputation: 889

Rails - Render active partial on same page?

So i just attach a screenshot to make it more obvious what im trying to do:

enter image description here

Is there a way to load a partial dynamically based on which button was pressed?

For example: If Customers is pressed, load the customer partial on the right side. If products, the products partial and so on.

I saw somewhere in some literature some examples where they did that, but can't find it anymore.

Thanks in advance everyone!

Greetings!

Upvotes: 1

Views: 357

Answers (1)

code_aks
code_aks

Reputation: 2074

I think you can do this in very easier way... Suppose your button is loaded on index page :-

#index.html.erb

.....
  #Your index page code
.....
<%= link_to “customer path”, customer_path, class: "css-class", remote: true %> ## create button with remote true for ajax call
<%= link_to “product path”, product_path, class: "css-class", remote: true %> ## create button with remote true for ajax call

   <div id = "customer-section"> </div> #div to load partials
   <div id = "product-section"> </div> #div to load partials

In your controller:

#controller.rb

def customer
 #customer code here
 respond_to do |format|
  format.js  {}
 end
end

def product
 #product code here
 respond_to do |format|
  format.js  {}
 end
end

Create js file :-

# customer.js.erb
$("#customer-section").html("<%=j render "customer")%>");

# product.js.erb
$("#product-section").html("<%=j render "product")%>");

Create partial html file to render :-

# _customer.html.erb
<h1>This is customer partial</h1>


# _product.html.erb
<div>This is product partial</div>

This way you can achieve your above requirement. For more you can refer this article https://m.patrikonrails.com/how-to-make-ajax-calls-the-rails-way-20174715d176

Hope this will help you. :)

Upvotes: 1

Related Questions