使用路由名称空间访问实例变量

时间:2014-11-20 09:52:23

标签: ruby-on-rails

的routes.rb

  resources :academies do
    resources :posts
  end

网址: / academies / 1 / posts

<%=link_to edit_academy_path(@academy) do %>
   <i class="fa fa-university"></i> <span>My academy</span>
<% end %>

但我收到此错误

No route matches {:action=>"edit", :controller=>"academies", :id=>nil} missing required keys: [:id]

因为它不存在 @academy

如何在/ academies / 1 / *资源的每个子路径中访问@academy?

1 个答案:

答案 0 :(得分:2)

您只需使用posts_controller

before_filter的每个操作中进行设置即可
class PostsController < ApplicationController
  before_filter :find_academy
  # ...
  private
  def find_academy
    @academy = Academy.find(params[:academy_id])
  end
end