我想使用两个不同的选择按钮显示在视图中选择的国家/地区和年份。
国家/地区选择:
<ul id = "countries">
<% @countries.each do |c| %>
<li><%= link_to c.name, {controller: "things", action: "graph", :id => c.id}, remote: true -%></li>
<% end %>
</ul>
年份选择:
<ul id = "years">
<% years=[2009,2010,2011,2012] %>
<% years.each do |y| %>
<li><%= link_to y, {controller: "things", action: "graph", :id=> y}, remote: true -%></li>
<% end %>
</ul>
路线:
get 'things/graph/:id' => 'things#graph' #I want to specify this one for country
get 'things/graph/:id' => 'things#graph' #I want to specify this one for year
控制器:
def graph
@country = Country.find(params[:id])
@year = params[:id]
@data = [@country, @year]
render js: "alert('The country and year is: #{@data}')"
end
选择国家/地区后,生成的警报为:
The country and year is: [#<Country id: 41, name: "Madagascar", created_at: "2017-04-14 05:50:13", updated_at: "2017-04-14 05:50:13">, "41"]
显示的年份值为&#34; 41&#34;这是国家ID,因为我尚未点击年份选择按钮。我希望控制器记住上一个选择中选择的年份,或者如果尚未完成选择则使用默认值。 当我选择2011年时,我收到错误:
ActiveRecord::RecordNotFound (Couldn't find Country with 'id'=2011):
我希望控制器记住上一个选择中选择的国家/地区。 如何获取两个选项(国家和年份)并将它们组合成一个数组以供进一步使用?