无法在轨道中单击按钮时传递参数

时间:2014-07-29 17:23:07

标签: ruby-on-rails ruby routes

我有一个控制器models_controller.rb如下:

class ModelsController < ApplicationController
  def list
    @models=["A","E","M","I"]
  end

  def get_config
    Rails.logger.info(params[:model_id])
    //some logic based on params[:model_id] value
  end
end

相应的list.html.erb如下:

<table>
  <thead>
  <tr>
    <th>Model</th>
    <th></th>
  </tr>
  </thead>
  <tbody>
  <% @models.each_with_index do |model, index| %>
      <tr>
        <td><%= model %></td>
        <td><%= button_to "view", {:controller => :models, :action => :get_config, :model_id => index }, :method => :get %></td>
      </tr>
  <% end %>
  </tbody>
</table>

这个表的每一行都有一个按钮,点击后,我传递元素的索引。但是我无法在get_config方法中访问它。记录器正在打印一个空字符串。 routes.rb如下:

DemoApp::Application.routes.draw do
  get "models/list"
  get "models/get_config"

  get "models/list/:model_id" => "models#get_config"
end

我做错了什么?我无法理解这一点。

1 个答案:

答案 0 :(得分:0)

Rails路由按照指定的顺序进行匹配。因此get "models/get_config"正在get "models/list/:model_id" => "models#get_config"之前捕获请求。尝试将订单更改为:

DemoApp::Application.routes.draw do
  get "models/list"
  get "models/list/:model_id" => "models#get_config"
  get "models/get_config"
end