rails – 如何使用参数进行GET请求操作

我希望这个问题相当简单,因为我对rails开发相对较新。 我试图从具有指定操作的控制器发出get请求并传递所需的参数。 这是助手类中的相关代码:

module ChartsHelper def chart_tag (action, height, params = {}) params[:format] ||= :json path = charts_path(action, params) content_tag(:div, :'data-chart' => path, :style => "height: #{height}px;") do image_tag('loading.gif', :size => '32x32', :class => 'spinner') end end end 

以及ChartsController中的相应操作:

 class ChartsController  { :type => 'AreaChart', :cols => [['string', 'Date'], ['number', 'subscriptions']], :rows => (1..days).to_a.inject([]) do |memo, i| date = i.days.ago.to_date t0, t1 = date.beginning_of_day, date.end_of_day subscriptions = Kpsevent.all.count memo < { :chartArea => { :width => '90%', :height => '75%' }, :hAxis => { :showTextEvery => 30 }, :legend => 'bottom', } } end end 

routes文件包含以下内容:

 resource :charts do get 'week_events_bar_chart' end 

但是,在尝试执行此请求时,我得到以下输出:

  Started GET "/charts.week_events_bar_chart?days=14" for 127.0.0.1 at Tue May 22 00:31:48 +1200 2012 Processing by ChartsController#index as Parameters: {"days"=>"14"} 

并且从不调用控制器动作。 有人能够帮助解决这个问题吗?

编辑:rake路线输出:

 week_events_bar_chart_charts GET /charts/week_events_bar_chart(.:format) {:controller=>"charts", :action=>"week_events_bar_chart"} POST /charts(.:format) {:controller=>"charts", :action=>"create"} new_charts GET /charts/new(.:format) {:controller=>"charts", :action=>"new"} edit_charts GET /charts/edit(.:format) {:controller=>"charts", :action=>"edit"} GET /charts(.:format) {:controller=>"charts", :action=>"show"} PUT /charts(.:format) {:controller=>"charts", :action=>"update"} DELETE /charts(.:format) {:controller=>"charts", :action=>"destroy"} 

您对控制台的评论:

在rails中, chart_path(x,...)将使用param id = x生成到ChartsController#show的路由,默认情况下为GET /charts/x 。 通过命名参数’action’,你自欺欺人,’week_events_bar_chart’将只是restful路径中的id。

对于你的原始代码: charts_path(x, params)将路由到格式为x的GET /charts.week_events_bar_chart ,它看起来像GET /charts.week_events_bar_chart ,再次称它为动作欺骗了你。

您需要的是您的操作的命名路径助手week_events_bar_chart_charts_path

但由于您似乎希望您的助手操作依赖,我建议您使用url_for。 http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-url_for

 module ChartsHelper def chart_tag(action, height, params = {}) params[:format] ||= :json url = url_for({:action => action, :controller => 'charts'}.merge(params)) content_tag(:div, :'data-chart' => url, :style => "height: #{height}px;") do image_tag('loading.gif', :size => '32x32', :class => 'spinner') end end 

结束

如果你真的想要完整路径,你可以传递:only_path => false到url_for。

您是否尝试使用斜线访问路线而不是charts后的句号?

 /charts/week_events_bar_chart?days=14 

而不是

 /charts.week_events_bar_chart?days=14