2017-07-02 100 views
-1

我需要表單的選定值以某種方式傳遞給我的控制器。我不確定我在路線和控制器中放置什麼來獲得價值。rails,如何將我的collection_select值傳遞給控制器​​

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' 

我測試了什麼? 我測試了我的代碼,它給了我這個URL。

當前結果: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 
+0

你的鏈接將無法工作,因爲它是一個'localhos t'! – Pavan

+0

http://guides.rubyonrails.org/routing.html – Pavan

+0

它顯然不會工作......我還沒有解僱它...... @Pavan – Napmi

回答

1

這裏是關於一些修正你的以上代碼

your routes.rb

resources :reports do 
    collection { 
    post :add 
    } 
end 

您show.html.erb, 這是編輯的版本你報告了一個錯誤之後,實際上只是去掉了「(...)」看到的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 

您可以檢查定製路線軌獲取和傳遞數據this link

+0

嗨,感謝您的幫助! 我試過了,它返回一個錯誤。將在上面發佈。 – Napmi

+0

好的抱歉的問題,我糾正了我的答案,我已經在我的系統中測試了上面的答案,我可以根據你的要求得到params [:cname] – widjajayd

相關問題