Rails创建非平凡路由的应用程序内链接的方法?

时间:2012-06-03 19:28:30

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1 routes

我一直在挖掘routing文档,似乎只发现了这个文档所需的一半必要信息。

如果我创建一个看起来像这样的路线:

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失败之后将我得到的内容粘贴起来。

1 个答案:

答案 0 :(得分:4)

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

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

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

  1. route_name_path:网址的路径,没有方案,主机名,......
  2. route_name_url:完整的网址,包括方案,主机名,...
  3. 这些方法将按顺序使用其参数作为路径的参数值,因此您可以说:

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

    :attendancesatt:newstatus等。或者,您可以将哈希传递给方法并直接使用参数名称:< / p>

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