如果您向我们提供有关您的数据模型的更多信息,将会很有帮助。我会根据你的问题勾勒出我认为你有什么。
class Product < ActiveRecord::Base
belongs_to :category
end
class Category < ActiveRecord::Base
has_many :products
end
并假设您已设置路线:
resources :categories do
resources :products
end
您需要做的是连接select_tag 的change 事件,以请求基于所选类别ID 的产品列表。
$('select#categories').change(function(){
var category_id = $(this).find('option:selected').val();
$.getJSON(
'/categories/' + category_id + '/products',
function(response) {
// render your template on the page here
}
);
});
我写了一个jQuery plugin 来简化与 Rails 控制器的基本 RESTful 交互,所以它可以写成:
$('select#categories').change(function(){
var category_id = $(this).find('option:selected').val();
$.read(
'/categories/{category_id}/products',
{ category_id: category_id },
function (response) {
// render your template
}
);
});
虽然$.read 并不比$.getJSON 简单多少,但其他操作将为您节省大量输入。
实现的其余部分在控制器中,但是您在如何实现方面还有很多余地,所以如果没有更多信息,我真的无法猜测什么会对您有所帮助。