2011-10-12 90 views
2

我有一個購物車應用程序,您可以從目錄中選擇產品。我想根據選擇動態填充幾列,如可用顏色,全部通過ajax。動態選擇與導軌和jQuery

這是我的看法,當你添加新項目

<td><%= f.collection_select(:product_id, Product.active.all, :id, :name, :prompt => 'Select Product') %></td> 
<td><%= f.text_field :quantity, :size => 6 %></td> 
<td><%= f.collection_select(:color_id, Color.all, :id, :name, :prompt => 'Select Color') %></td> 
<td><%= f.text_field :price, :size => 8 %></td> 
<td><%= f.link_to_remove "remove" %></td> 

我想根據的product_id值來設定價格和顏色選擇。這是我到目前爲止:

$('select#order_items_new').change(function() { 
    // How to retrieve table columns based on product_id value? 
}); 

回答

1

我希望能夠準確地瞭解您的挑戰。一旦選擇了產品,顏色選擇將通過ajax和價格顯示出來。

這裏是產品選擇。

<%= form_tag "some_form" do |f| %> 
    Choose a product: 
    <%= select_tag "product_id", options_for_select(@products.collect { |p| [p.name, p.id]}), :include_blank => true %> 
    <br> 
    <div id="colors_select"></div> 
<% end %> 

當產品選擇發生變化時,ajax就會啓動並檢索產品顏色和價格。

$(document).ready(function() { 
    $("#product_id").live("change", function() { 
    $.ajax({ 
     url: '/get_colors', 
     data: { 
     product_id: $(this).val(); 
     }, 
     cache: false, 
     success: function(html) { 
     $("#colors_select").html(html); 
     } 
    }); 
    }); 
}); 

不要忘記包含返回顏色方法的路線。

App::Application.routes.draw do 
    match 'get_colors' => 'colors#get_colors' 

一個簡單的方法,返回與顏色和價格的部分。一旦你的關聯設置好了,你可以通過Product.find(params [:product_id])獲得特定產品的顏色。顏色

class ColorsController < ApplicationController 

    def get_colors 
    @colors = Color.all 
    @price = Product.find(params[:product_id]).price 
    render :partial => 'get_colors' 
    end