rails,如何将我的collection_select值传递给控制器

时间:2017-07-02 16:15:18

标签: ruby-on-rails forms routes

我需要将表单的选定值以这种或那种方式传递给我的控制器。我不确定我在路线和控制器中放置了什么来获得价值。

show.html.erb

<h1>Report#show</h1>

<%= form_tag new_report_path(:cname) do %>
  <label for="lookup">Lookup</label>
  <%= collection_select(:cname, 2, Company.all, :id, :name) %>
  <%= submit_tag "Submit" %>
<% end %>

控制器report_controller.rb

def show
end

def add 
  # how do i get the :cname here?
end

路线

  root 'report#show'
  get '/report/index' => 'report#show'

我测试了什么? 我测试了我的代码,它给了我这个网址。

当前结果:http://localhost:3000/report/new.cname

预期结果:http://localhost:3000/report/:cname

******** ****** UPDATE

我测试了widjajayd的解决方案。 它把这个错误还给了我.. 我也在这里提供了控制器名称 enter image description here

这是我的佣金路线

               add_reports POST       /reports/add(.:format)                    reports#add
                   reports GET        /reports(.:format)                        reports#index
                           POST       /reports(.:format)                        reports#create
                new_report GET        /reports/new(.:format)                    reports#new
               edit_report GET        /reports/:id/edit(.:format)               reports#edit
                    report GET        /reports/:id(.:format)                    reports#show
                           PATCH      /reports/:id(.:format)                    reports#update
                           PUT        /reports/:id(.:format)                    reports#update
                           DELETE     /reports/:id(.:format)                    reports#destroy
             company_index GET        /company(.:format)                        company#index
                           POST       /company(.:format)                        company#create
               new_company GET        /company/new(.:format)                    company#new
              edit_company GET        /company/:id/edit(.:format)               company#edit
                   company GET        /company/:id(.:format)                    company#show
                           PATCH      /company/:id(.:format)                    company#update
                           PUT        /company/:id(.:format)                    company#update
                           DELETE     /company/:id(.:format)                    company#destroy
                      root GET        /                                         report#show

1 个答案:

答案 0 :(得分:1)

这里有一些关于上面代码的更正

your routes.rb

resources :reports do
  collection {
    post :add
  }
end

你的show.html.erb, 这是您报告错误后编辑的版本,实际上只是删除了&#34; (...)&#34;见form_tag

<%= form_tag add_reports_path, :method => 'post' do  %>
  <label for="lookup">Lookup</label>
  <%= collection_select(:cname, 2, Company.all, :id, :name) %>
  <%= submit_tag "Submit" %>
<% end %>

您的控制器(我在路线内创建了集合)

def add 
  your_cname = params[:cname]
end

您可以检查rails获取和传递数据的自定义路由this link