I have a select_tag which displays product category types. I want to do an Ajax update when a user selects a product category and list down all the products in a div below the select tag.
I think I'll be able to handle the product display par开发者_JAVA技巧t with a partial and js template. But i dont know how to implement the
product category selection doing an ajax request (with parameters) to rails controller. (Almost all the examples in web is bind with ajax form updation....)
can someone help me out- thanks in advance
I'm using rails 3, Jquery
cheers
sameera
It would be helpful if you gave us more information about your data models. I'll sketch out what I think you have based on your question.
class Product < ActiveRecord::Base
belongs_to :category
end
class Category < ActiveRecord::Base
has_many :products
end
and assuming you have your routes set up:
resources :categories do
resources :products
end
what you need to do is wireup the change
event of the select_tag
to request a list of products based on the category id that was selected.
$('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
}
);
});
I've written a jQuery plugin to simplify basic RESTful interactions with a Rails controller, so it could be written as:
$('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
}
);
});
While $.read
isn't much simpler than $.getJSON
, the other operations will save you a lot of typing.
The rest of the implementation rests in the controller, but you have a lot more leeway in how to implement that, so I can't really guess what would be helpful to you without more information.
精彩评论