Dynamic Partial Based on Select Box - Rails 2.3.5

前端 未结 1 1829
有刺的猬
有刺的猬 2021-01-06 15:27

I\'ve edited my request to hopefully be clearer. I need to render a partial dynamically based on a previous selection box.

REQUEST belongs to PRODUCT

PRODUC

相关标签:
1条回答
  • 2021-01-06 16:05

    one reminder first before we start. I'm not sure about this but I think request is a reserved word in rails.

    JS

    this just observes the dropdown and performs an ajax call

    $(document).ready(function() {
      $('#request_product_id').change(function() {
        $.ajax({ url: '/products/' + this.value + '/form_partial' });
      });
    });
    

    ROUTES

    nothing fancy here either. Just setting up a route where the ajax will go to when it is triggered

    resources :products do
      get :form_partial, on: :member
    end
    

    CONTROLLER

    we just fetch the product using :id which is passed from ajax

    def form_partial
      @product = Product.find params[:id]
    end
    

    JS TEMPLATE

    you need to create a form_partial.js.erb which will render the partial depending on the product. The code below appends the partial after the product_field div

     # app/views/products/form_partial.js.erb
     $('#product_partial').remove();
     <% if @product.id == 1 %>
       $('#product_field').after('<div id="product_partial"><%= escape_javascript render('partial1') %></div>');
     <% else %>
       $('#product_field').after('<div id="product_partial"><%= escape_javascript render('partial2') %></div>');
     <% end %>
    

    UPDATE: for rails 2.x

    we just need to change the routes and the js template in order for this to run on rails 2.x

    ROUTES 2.x

    map.resources :products, member: { form_partial: :get }
    

    JS TEMPLATE 2.x

    if I remember correctly, the file should be named form_partial.js.rjs. This will give you a page variable which you can use to add js.

     # app/views/products/form_partial.js.rjs
     page << "$('#product_partial').remove();"
     page << "<% if @product.id == 1 %>"
     page << "  $('#product_field').after('<div id="product_partial"><%= escape_javascript render('partial1') %></div>');"
     page << "<% else %>"
     page << "  $('#product_field').after('<div id="product_partial"><%= escape_javascript render('partial2') %></div>');"
     page << "<% end %>"
    
    0 讨论(0)
提交回复
热议问题