1

我一直在研究路由文档,似乎只发现了这个所需信息的一半。

如果我创建一条如下所示的路线:

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

恐怕我完全不清楚如何创建一个link_to能够满足上述要求的适当咒语。

例如,创建此 URL 似乎没有问题:

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:继续“mu太短”的建议,这是我的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

如果有兴趣,我会粘贴尝试重新启动 WEBrick 失败后得到的内容。

4

1 回答 1

4

首先,您要为路线命名,以便获得适当的辅助方法:

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

这将生成两种可用于构建 URL 的方法:

  1. route_name_path: URL 的路径,无方案,主机名,...
  2. route_name_url: 完整的 URL,包括方案、主机名、...

这些方法将按顺序将它们的参数用于路由的参数值,因此您可以说:

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

and :attendanceswould be att, :newwould bestatus等。或者,您可以将 Hash 传递给方法并直接使用参数名称:

<%= link_to 'Pancakes!', route_name_url(
    :attendances => att,
    :new         => status,
    :class_date  => date,
    :student_id  => id
) %>
于 2012-06-03T19:43:35.490 回答