我正面临着这个困难。这对我有用:
<% cat_st = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29 %>
<%= Categories.where(cat_id: [cat_st]).distinct.count(:af_id) %>
但是,我需要从我的GET参数创建cat_st字符串。当我将其创建为字符串时,它只获得第一个整数。实际上,我真的不知道cat_st变量是什么。我试图创建一个数组,但它不起作用。有任何想法吗?
(它不起作用)
<% cat_st = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29' %>
<%= Categories.where(cat_id: [cat_st]).distinct.count(:af_id) %>
答案 0 :(得分:0)
cat_st = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29'
cat_array = cat_st.split(',')
Categories.where(cat_id: cat_array).distinct.count(:af_id)
如果您提供有关您尝试执行的操作的其他详细信息,可能有更好的解决方案可以实现您想要实现的目标,似乎它应该是某种通过多个ID的搜索表单。像这样的东西:
class Search
include ActiveModel::Model
attr_accessor :category_ids
end
<%= form_for Search.new, url: 'whatever_the_url_is' do |f| %>
<div class="field">
<%= f.label :category_ids %>
<%= f.collection_check_boxes :category_ids, Category.all, :id, :name %>
</div>
<% end %>
search = Search.new(search_params)
Categories.where(cat_id: search.category_ids).distinct.count(:af_id)
答案 1 :(得分:0)
您只能将范围传递给where
方法,所以:
Categories.where(cat_id: (1..29)).distinct.count(:af_id)
并通过 GET 请求传递数据只需使用限制:
控制器:
def action
@cat = Categories.where(cat_id: (params[:begin].to_i..params[:end].to_i)).distinct.count(:af_id)
end
然后使用@cat
变量渲染视图。
答案 2 :(得分:0)
如果在URL查询中为参数名称添加方括号,Rails(特别是Rack)会将其解释为数组:
http://some.route.url/path?foo[]=bar&foo[]=buzz
控制器会将params[:foo]
读为['bar', buzz']
但是,我觉得您试图解决的用例问题可能有一个更简单的解决方案。关注更多细节?