ashr81
ashr81

Reputation: 650

Ruby on Rails:Reload a View Inside other

I has two views named _show.html.erb and index.html.erb.
_show.html.erb is rendered inside index.html.erb.
I want to reload only _show.html.erb part inside index.html.erb.
when a dropdown is selected.

tests/_show.html.erb file:

<div class="main_content" >
<% @tests.each do |x| %> 
        <%# if x.name ==  @str %>
        <p>Here it is <%= x.name %> your rating in Programming languages</p>
        <% x.languages.each do |a,b| %> 
            <%= a %> <strong> : </strong> <%= b*10 %></br>
        <% end %>
        <p>State: <strong><%=x.state%></strong></p>
        <%# end %>
<% end %>
</div>

tests/index.html.erb file:

<p>Find me in app/views/tests/index.html.erb</p>
<%= select_tag :name,options_for_select(@tests.map{|u| [u.name]}.uniq), remote: true, id: "update_select" %>
<% @str = "<span id=\"product-modal\">Ashrith</span>".html_safe %>
        <%= @str %>
    <%= render "show" %>

application.js file:

$(document).ready(function(){
    $("#update_select").change(function()
    {
        drop = $(this).val();
        alert(drop);
        $("#product-modal").html(drop);
    });
});

From the above files.As the dropdown is selected the value of dropdown should be equated in the _show.html.erb.Any methodology,other than this is OK.more rubist,more good.

Upvotes: 0

Views: 93

Answers (1)

Pierre Pretorius
Pierre Pretorius

Reputation: 2909

Let's assume you are rendering posts. I would let the Posts#index action respond to html and js. On html it renders the entire page, on JS it only replaces the posts on the page and not the filters (which is one dropdown in your case). Furthermore since you tend to need multiple filters on a page, I like to place all the filters in a form that auto submits. Example:

<%= form_tag posts_path, remote: true, method: :get, data: {bind: true} %>
  ... Place filtering dropdowns and other controls here...
<% end %>

<div id="posts">
  <%= render @posts %>
</div>

<script type="text/javascript">
  $("form[data-bind]").find('input').on('change', function () {
    $(this).closest('form').submit);
  });
</script>

Note the JS above doesn't have to be placed in the view file, it's just there to make the example simple. It's JS that you can place and use project wide. The controller:

 class PostsController
   def index
     @posts = Post.all
     @posts.where(some_field: params[:some_form_filter) if params[:some_form_filter]

     respond_to do |format|
       format.html
       format.js
     end
   end
 end

The JS response replaces places the page content with jquery in app/views/posts/index.js.erb:

 $('#posts').html("<%= j(render @posts %>");

NB: This writeup was done from the hip so you might need to correct minor things here and there.

Upvotes: 1

Related Questions