2012-06-03 13 views
1

我一直在挖掘routing文檔,似乎只發現了這一個所需的一半所需的信息。Rails如何創建非重要路線的應用內鏈接?

如果我創建它看起來像一個路線:

match 'attendances/new/:class_date/:student_id' 

我怕我對如何建立適當的link_to咒語,它能夠滿足上述的完全不清楚。

例如,我似乎沒有問題創造這個網址:

http://localhost:3000/attendances/new?class_date=2012-05-07&student_id=5 

,但我還沒有找到合適的文檔,說明如何創建這樣的:

http://localhost:3000/attendances/new/2012-05-07/5 

有人能提供一個有用的例子和/或文檔的鏈接,討論如何做到這一點?

我意識到嘗試使用link_to在這裏可能完全不合適。我意識到我可以在一起編寫一些代碼來製作適當的鏈接,但我懷疑這樣做會完全錯過一些更好的Ruby on Rails方式來做到這一點。

編輯:更正了以上提議的match路線。

編輯2:你打算在 「萬畝太短」 的建議,這裏就是我的routes.rb現在看起來像:

NTA::Application.routes.draw do 
    resources :students 

    resources :libraries 

    resources :year_end_reviews 

    resources :notes 

    resources :ranktests 

    resources :attendances 

    match 'attendances/new/:class_date/:student_id', :as => :add_attendance 

    resources :ranks 

    get "home/index" 

    root :to => "home#index" 

end 

和這裏的相關觀點:

<% today = Date.today %> 
<% first_of_month = today.beginning_of_month %> 
<% last_of_month = today.end_of_month %> 
<% date_a = first_of_month.step(last_of_month, 1).to_a %> 
<h2><%= today.strftime("%B %Y") %></h2> 

<table id="fixedcolDT"> 
<thead> 
    <tr> 
    <th>Name</th> 
    <% date_a.each do |d| %> 
     <th><%= d.day %></th> 
    <% end %> 
    </tr> 
</thead> 

<tbody> 
<% @students.each do |s| %> 
    <tr> 
    <td><%= s.revfullname %></td> 
    <% date_a.each do |d| %> 
     <% student_attend_date = Attendance.find_by_student_id_and_class_date(s.id, d) %> 
     <% if student_attend_date.nil? %> 
      <td><%= link_to "--", add_attendance_path(d, s.id) %></td> 
     <% else %> 
      <td><%= student_attend_date.class_hours %></td> 
     <% end %> 
    <% end %> 
    </tr> 
<% end %> 
</tbody> 
</table> 

和這裏是我最初重新加載後(在嘗試重新啓動WEBrick之前)返回的內容:

ArgumentError 

missing :controller 
Rails.root: /Users/jim/Documents/rails/NTA.new 

Application Trace | Framework Trace | Full Trace 
config/routes.rb:15:in `block in <top (required)>' 
config/routes.rb:1:in `<top (required)>' 
This error occurred while loading the following files: 
    /Users/jim/Documents/rails/NTA.new/config/routes.rb 

我將pastebin我回來瞭如果有興趣,我嘗試重新啓動WEBrick後失敗。

回答

4

首先,你想給的路線的名稱,這樣你會得到相應的輔助方法:

match ':attendances/:new/:class_date/:student_id' => 'controller#method', :as => :route_name 

,將產生兩種方法,您可以用它來建立的網址:

  1. route_name_path:爲URL,沒有方案,主機名的路徑,...
  2. route_name_url:完整的URL,包括方案,主機名,...

這些方法將使用他們的路由的參數值參數,以便所以你可以說:

<%= link_to 'Pancakes!', route_name_path(att, status, date, id) %> 

:attendancesatt:newstatus等。或者,你可以通過一個哈希方法和直接使用的參數名:

<%= link_to 'Pancakes!', route_name_url(
    :attendances => att, 
    :new   => status, 
    :class_date => date, 
    :student_id => id 
) %> 
+0

很大的相關詳細答案,像往常一樣... +1 :) – apneadiving

+0

遇到了一些麻煩,似乎我所提出的'match'規則不是我想要的。將編輯,然後分享接下來發生的事情。 – caffecaldo

+0

因此,在嘗試實施建議後,我在頁面上重新加載。它拋出一個'missing:controller' ArgumentError。所以我嘗試重新啓動WEBrick,並在technicolor(然後退出)中噴出,基本上是指出的ArgumentError的詳細版本。如果我在原始問題中增加更多細節,也許會更好。 – caffecaldo