筛选类别 [英] Filtering categories
问题描述
在我的应用程序中,我有一个提供程序列表,每个提供程序都有类别.我的模型如下:
In my app I have a list of providers, and each provider has categories. My models look as follows:
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
在一个视图中,我有2个ul
列表.第一个是提供者列表,第二个是类别列表.看起来像:
In a view, I have 2 ul
lists. The first one is a list with providers, and the second one - a list of categories. It looks like:
<ul class="nav nav-justified nav-carousel upper-thumbs">
<% Provider.order(created_at: :asc).take(6).each_with_index do |provider, index| %>
<li id="<%= provider.name %>_<%= index + 1 %>" class="btn-up"><a data-href="#"><%= provider.name %></a></li>
<% end %>
</ul>
<ul id="parent" class="nav nav-justified nav-carousel left-thumbs">
<% Category.order(created_at: :asc).take(7).each_with_index do |category, index| %>
<li id="aside_<%= index + 1 %>" class="btn-aside"><i class="category_image" style="background: url(<%= category.cat_image %>) no-repeat;"></i><a data-href="#"><%= category.name %></a></li>
<% end %>
</ul>
当我没有实现Rails的时候,当我单击提供程序(它也被硬编码,以及类别)时,我可以看到,类别已被过滤.它是由js制造的:
When I had no rails implementation, when I clicked on the provider (it was hardcoded, as well, as the categories), I could see, the categories were filtered. It was made by 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');
})
所以,问题是如何使过滤器起作用,所以当我单击一个提供程序时,它将仅显示属于该提供程序的类别?谢谢.
So,the question is how to make the filter work, so when I click on a provider, it will show me only the categories, which belongs to that provider? Thanks.
推荐答案
Ajax是执行此类操作的最佳方法.
Ajax is best way to do this kind of things.
例如.
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;
}
});
})
SomeContoller.rb
def some_method
@provider = Provider.find_by_id(params[:provider])
@categories = @provider.categories
respond_to do |format|
format.json { render json: @categories}
end
end
这篇关于筛选类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!