当选择大分类的时候 小分类跟着改变
model
class Category < ActiveRecord::Base
has_many :subcategories
end
class Subcategory < ActiveRecord::Base
belongs_to :category
end
view
<%= collection_select(:usedbook,:name,@categories,:id,:name) %>
<span id="next_select"> <%= collection_select(:usedbook,:subcategory_id,@subcategories,:id,:name) %> </span>
<%= select(:usedbook, :subcategory_id, @subcategories) %>
控制器
def select_with_ajax
@subcategories=Subcategory.all(:conditions => ["category_id=?",params[:category_id]]).collect{|subcategory|
[subcategory.name,subcategory.id]}
render(:layout=>false)
end
Jquery
$('#usedbook_name').change(function(){
v =$(this).val();
$("#next_select").hide();
$('#next_select').load("select_with_ajax",{category_id:v}).show();
});