each_with_index仅显示最后一个选项

时间:2014-03-24 07:37:56

标签: ruby-on-rails ruby-on-rails-3.2

我使用Gruff with Prawn插入图像图表,我的条形图显示正确,但标签只显示最后一个标签。 See image here for example

使用对虾(0.15.0)和粗暴(0.5.1)

def initialize(result)
 super()
 @result = result
 show_graph
end

def show_graph
lint = @result.map {|v| v.lint/227 } 
g = Gruff::Bar.new('540x200')
g.data(:lint, lint, '#00463f')
@result.each_with_index do |v, i|
g.labels = {i => v.variety.variety_name}
end
g.y_axis_label = 'Yield (bales/ha)'
g.marker_font_size = 16
g.marker_count = 5
g.theme = {:marker_color => '#333333', :font_color => '#333333', :background_colors => %w(#ffffff #ffffff)}
g.minimum_value = 0
g.hide_legend = true

g.write("#{Rails.root}/app/assets/images/chart.png")

image "#{Rails.root}/app/assets/images/chart.png"

结束

控制器

@result = Result.where('trial_id' => params[:trial_id]).order('lint DESC')

1 个答案:

答案 0 :(得分:1)

您犯的错误是您在每次迭代时重新定义标签哈希。 而不是做

g.labels = {i => v.variety.variety_name}

尝试:

g.labels[i] = v.variety.variety_name

在每个之前,你可以把:

g.labels = {}