Jquery 过滤类别
在我的应用程序中,我有一个提供商列表,每个提供商都有类别。我的模型如下所示:Jquery 过滤类别,jquery,ruby-on-rails,filtering,Jquery,Ruby On Rails,Filtering,在我的应用程序中,我有一个提供商列表,每个提供商都有类别。我的模型如下所示: class Categorization < ApplicationRecord belongs_to :category belongs_to :provider end class Category < ApplicationRecord has_many :categorizations has_many :providers, through: :categorizations
class Categorization < ApplicationRecord
belongs_to :category
belongs_to :provider
end
class Category < ApplicationRecord
has_many :categorizations
has_many :providers, through: :categorizations
accepts_nested_attributes_for :categorizations
end
class Provider < ApplicationRecord
has_many :categorizations
has_many :categories, through: :categorizations
accepts_nested_attributes_for :categorizations
end
当我没有rails实现时,当我点击提供者时,它是硬编码的,我可以看到,类别也被过滤了。它是由js制作的:
var $btns = $('.btn-up').click(function () {
if(this.id == 'a') {
$('#parent > li#aside_1').fadeIn(450);
$('#parent > li').not($('#parent > li#aside_1')).hide();
} else {
var $el = $('.' + this.id).fadeIn(450);
$('#parent > li').not($el).hide();
}
$btns.removeClass('active');
$(this).addClass('active');
})
所以,问题是如何使过滤器工作,所以当我点击一个提供者时,它将只显示属于该提供者的类别?谢谢。Ajax是做这类事情的最佳方式 前
因此,这里有一种方法可以实现这一点 您可以在每次单击提供程序获取其关联类别并使用JQuery将其附加到HTML时发送AJAX请求 在这里粘贴的代码非常复杂,因此我建议您仔细阅读此视频,了解它是如何工作的,并以适合您的方式实现它 Ryan Bates在下面的视频中很好地解释了这个概念
我在一个视图中添加了一个链接:,这样现在我就可以将propper参数传递给controller,并从json中传入对done propper值的ajax调用,但似乎没有什么变化,类别仍然是一样的,它们不会以更为rails的方式清空它,通过创建一个文件some_method.js.erb,在该文件中我完成了所有需要的操作。Thaks为了你的回答,它把我推向了正确的方向。
var $btns = $('.btn-up').click(function () {
if(this.id == 'a') {
$('#parent > li#aside_1').fadeIn(450);
$('#parent > li').not($('#parent > li#aside_1')).hide();
} else {
var $el = $('.' + this.id).fadeIn(450);
$('#parent > li').not($el).hide();
}
$btns.removeClass('active');
$(this).addClass('active');
})
var $btns = $('.btn-aside').click(function () {
var provider_id = 'get selected provider via JS'
$.ajax({
type: "POST",
url: "/some_url_of_controller_method",
data: {
provider: provider_id
},
success: function(data) {
$('.btn-up').empty()
$.each(data, function(){
$('.btn-up').append('<option value="'+ this.value +'">'+ this.name +'</option>')
)
},
error: function(data) {
return false;
}
});
})
def some_method
@provider = Provider.find_by_id(params[:provider])
@categories = @provider.categories
respond_to do |format|
format.json { render json: @categories}
end
end