Ruby on rails Rails视图中的分组依据
在我的rails应用程序中,我有以下模型Ruby on rails Rails视图中的分组依据,ruby-on-rails,group-by,Ruby On Rails,Group By,在我的rails应用程序中,我有以下模型 Transaction belongs_to :account belongs_to :agent belongs_to :program 这是我用来获取数据的查询 def self.efficiency_report(starts=nil, ends=nil) sql = "SELECT p.abbreviation,ag.name, t.miles, t.date FROM transactions t
Transaction
belongs_to :account
belongs_to :agent
belongs_to :program
这是我用来获取数据的查询
def self.efficiency_report(starts=nil, ends=nil)
sql = "SELECT p.abbreviation,ag.name,
t.miles, t.date
FROM transactions t
inner join accounts a on t.account_id = a.id
inner join programs p on a.program_id = p.id
inner join agents ag on t.agent_id = ag.id
Group by p.id , ag.id"
result_array(sql)
end
def self.result_array(sql)
conn = ActiveRecord::Base.connection
res = conn.execute(sql)
results = []
res.each{|r|
results << r
}
return results
end
为此,在我看来,我正在做以下工作
%h2 Vendor Efficiency Report
- @transactions.group_by(&:row[0]).sort.each { |data, transaction|
%h2= data.row[0]
- transaction.group_by(&:row[1]).sort.each { |data, transaction|
%table#data_table.display{:cellpadding => "0", :cellspacing => "0"}
%h3{:style => "clear:both;margin-left:10px"}= data.row[1]
%thead
%tr.odd
%td.bold{:style => "width:60px;"} Miles
%td.bold{:style => "width:60px;"} Date
- for t in transaction
%tbody
%tr
%td{:style => "width:60px;"}= row[2]
%td{:style => "width:60px;"}= row[3]
-}
-}
= will_paginate @transactions
但我得到了这个错误
错误的参数类型字符串(预期过程)
有人会告诉我我做错了什么,或者有没有其他更好的分组方式
提前感谢问题在于您的
通话分组。我不确定&:row[0]
正在做什么,但它正在传递一个字符串作为参数。我想这就是你想要的:
@transactions.group_by{r|r[0]}。。。
编辑
刚刚弄清楚&:row[0]
在做什么。这是对Symbol#[]
方法的调用,该方法返回给定索引处的字符(本质上,就像它是字符串一样)。调用:row[0]
返回字符串“row”
的第一个字符
所以基本上,你好像在打电话:
@transactions.group_by(&"r")
有趣的是,我刚刚做了一些测试::行[0]
为您提供字符串的第一个字符“行”
(即“r”
)。奇怪的我以前从未见过这种语法。当我们从操作中得到完整的模式结果时,我们可以像这样使用:“@transactions.group_by(&:payment_date).sort.each{date,transaction |”如果payment_date在transactionOh中只有一列,则它不必是一个模型才能工作。您传递的参数必须是表示数组中对象的方法的符号。(实际上,如果您想要详细的答案,参数可以是定义了方法to_proc
的任何对象,这对符号是正确的,而不是字符串)。请尝试以下操作:%w[abc abc abc abc abc efg abcde]。排序依据(&:length)
@transactions.group_by(&"r")