2013-02-12 200 views
0

我想將當前項目的id傳遞給票據控制器(爲該項目創建票據),我在下面嘗試執行此操作。但是,我這樣做是通過以下方式給了我下面的鏈接:無法將project.id從視圖傳遞到控制器

tickets/new?project_id=8 

...當我只是希望它是這樣的:

tickets/new 

...即使我想要的PROJECT_ID在控制器中可訪問。

我該怎麼做?只是爲了澄清:我不希望project_id成爲URL的一部分,我只是想以某種方式將它作爲參數傳遞給控制器​​。

<h1><%= @project.title %></h1> <-- the project's attributes is reachable here 

<%= link_to "Create ticket", new_ticket_path(:project_id => @project.id), :class => "btn edit_button" %> 

門票控制器:

從視圖

1. class TicketsController < ApplicationController 
2.  def new 
3.   @ticket = Ticket.new 
4.   @id = params[:project_id] 
5. 
6.   @project = Project.find(@id) 
7.  end 
8. end 

的路線會的link_to點,如下所示:

new_ticket GET /tickets/new(.:format)   tickets#new 
+2

'new_ticket_path(:project_id => @project.id)'?你錯過了'@'? – fl00r 2013-02-12 19:03:24

+0

我也嘗試過,同樣的錯誤。雖然我認爲它應該與@所以我會編輯我的Q. – holyredbeard 2013-02-12 19:04:37

+0

html'link_to'生成什麼? – fl00r 2013-02-12 19:06:04

回答

0

如果門票貝隆g到項目中,您可能需要考慮嵌套資源。

現在,你的路線可能是這樣的:

resources :projects 
resources :tickets 

這會產生像/projects/new/tickets/new路線。你可以做的是這樣的:

resources :projects do 
    resources :tickets 
end 

這會給你像/projects/8/tickets/new路線。您通過做new_project_ticket_path(@project)鏈接到一張新票。路線生成的實際形式是:/projects/:project_id/tickets/:id。所以params [:project_id]會給你這個項目的id。

相關問題