我正在使用rails构建应用程序,并且我有一个items_controller,其中包含用于创建,显示,编辑,销毁等的方法应用程序。
但是,我正在尝试创建自己的方法来访问数据库特定列中的所有值,并且我很难在数组中捕获这些数据。
我尝试了以下捕获数据的方法(其中'quantity'是我要查找的数据库中的列):
@items = Item.find(params[:id])
@items2 = @item.find(params[:quantity])
我也尝试过:
@items = Item.find(params[:quantity])
&安培;甚至:
@items = Item.all
@items2 = @item.find(params[:quantity])
但是,这些方法似乎都不起作用。对于我正在做的事情,它甚至不是必不可少的 知道哪些数量列值与哪一行相关...只需获取列值列表就足够了。
如果有人知道这里有什么问题,非常感谢您的帮助!
感谢。
更新
为了清楚起见,我试图检索与items_controller相关联的数据库中特定列的所有数据,并过滤特定数据片段的数据(在本例中为字符串“7”) - 因为数据是从使用Items.all方法时db作为字符串。
然后,我希望每次在数量列中遇到“7”时计数器都会增加。
def chartItems
@items = Item.find(params[:id])
@items2 = @items.find(params[:quantity])
@filter = custom_filter_for(@items2)
def custom_filter_for(value)
j=0 # counter initialised at 0
value.each do |x|
if x == "7" # checking for data equal to "7" - the num is retrieved as a string
j = j+1 # increase j counter by 1 whenever "7" is encountered as a quantity
end
return j
end
end
答案 0 :(得分:0)
在这种情况下,您的find
参数将作为ID处理:
@items = Item.find(params[:quantity])
返回包含id
参数quantity
的所有项目。这显然不是你想要的。
您可以根据数量选择项目:
@items = Item.find_by_quantity(params[:quantity])
但是如果你只需要数组中的数量,这就是你要找的东西:
@quantities = Items.select(:quantity).map(&:quantity)
您更新的问题:
result = Items.find_by_quantity(params[:quantity]).count
答案 1 :(得分:0)
在ActiveRecord的新版本中,他们添加了pluck
,其基本上与@Matzi的select
和map
方法相同。
要获得所有商品数量,您可以
@quantities = Item.pluck(:quantity)
另外,我会仔细检查你对find_by
助手的使用情况。我认为find_by_quantity只会给你一个回匹(@item
,而不是@items
)。为了得到所有,我认为你真的想使用where
@quantities = Item.where(:quantity => params[:quantity])
如果您使用上面提到的pluck
,我认为您的过滤步骤也可以非常简洁地编写。该过滤器只是计算列表中7的数量,对吧?
@quantities = Item.pluck(:quantity)
@filtered_values = @quantities.select{|q| q == 7}.length
我希望这会有所帮助。