无法从控制器显示数组值多查询

时间:2015-01-13 15:31:24

标签: ruby-on-rails ruby ruby-on-rails-3

我试图从控制器每年每个月显示数组值,但没有显示任何内容。

以下是信息和演示:

CREATE TABLE player_scores (id INT,name text,date_score date,goals INT );
CREATE TABLE months (id INT,name text );

INSERT INTO player_scores VALUE
 ( 1, 'PIZARRO'   , '2015-01-02', 4),
 ( 2, 'ROBBEN'    , '2015-02-24', 2),
 ( 3, 'RIBERY'    , '2015-03-02', 4),
 ( 4, 'GOTZE'     , '2015-04-24', 2),
 ( 5, 'NEIWER'    , '2015-05-02', 4),
 ( 6, 'DANTE'     , '2015-06-24', 2),
 ( 7, 'LEWANDOSKI', '2015-07-02', 4),
 ( 8, 'RAFINHA'   , '2015-07-02', 4),
 ( 9, 'GUARDIOLA' , '2015-11-02', 3);

INSERT INTO months VALUE
 ( 1, 'jan'),
 ( 2, 'feb'),
 ( 3, 'mar'),
  ...      
 ( 12,'dec');

这是控制器:

def germany_world_cup
   @months= Month.all

   ## THIS LINE WILL REPEAT THE QUERY 12 TIMES FOR EACH MONTH JANUARY TO DECEMBER 
   @months.each do |m|
      @query = PlayerScore.find_by_sql("SELECT count(*) AS count_all FROM player_scores WHERE YEAR(date_score)=2015 AND MONTH(date_score)='#[m.id}' ")
   end
end

以下是有问题的视图(未显示值):

<% @query.each do |q| %> 
  <%= q.count_all %>  ### IS SHOWING only 0 as result
<% end %>

这是我的日志实际工作但未在视图中显示:

select count(*) as count_all from player_scores where month(date_score)=1 and year(date_score)=2015
select count(*) as count_all from player_scores where month(date_score)=2 and year(date_score)=2015
...
select count(*) as count_all from player_scores where month(date_score)=12 and year(date_score)=2015

根据rails sintaxis显示来自控制器的值

<% @var.each do |v| %>
   <%= v.column_name %>
<% end %>

我尝试使用此代码来检查值,但什么都没有:

<%= @query.inspect %>  ### I got " [#] " as result

我试过这段代码:

<% @query[0].each do |q| %> 
  <%= q.count_all %>   ### I GOT THIS ERROR "undefined method `each' "
<% end %>

我想在控制器中显示来自数组的值?

请有人告诉我显示价值观吗?

提前致谢。

1 个答案:

答案 0 :(得分:1)

避免@query变量覆盖的方法是使用#map

@query = @months.map do |m|
   PlayerScore.find_by_sql("SELECT count(*) AS count_all FROM player_scores WHERE YEAR(date_score)=2015 AND MONTH(date_score)='#[m.id}' ")
end