我试图更好地处理 Rail 的嵌套资源,并使用模型School和Class制作了一个测试应用程序。在我的routes.rb
文件中,我有:
resources :schools do
resources :classes
end
School和Class具有以下模型关系:
class School < ActiveRecord::Base
attr_accessible: name
has_many :classes
end
和
class Class < ActiveRecord::Base
attr_accessible: name, school_id
belongs_to :school
end
我很难获得school_id
与在诸如/schools/1/posts/new
. 更准确地说,我想定义一个这样的辅助方法current_school
,它可以使用它包含的 URI 的前半部分school_id
,以允许我在控制器中编写函数,这样current_school.posts.all
会自动拉取与school_id
=相关联的所有帖子网址。谢谢!
*编辑
这是我所拥有的ClassController
:
class ClassesController < ApplicationController
def index
@classes = current_school.classes.all
end
def new
@class = current_school.classes.build
end
def create
@class = current_school.classes.build(params[:post])
if @class.save
redirect_to root_path #this will be further modified once I figure out what to do
else
redirect_to 'new'
end
end
private
def current_school
@current_school ||= School.find(params[:school_id])
end
end
在new.html.erb
文件中:
<div class="span6 offset3">
<%= form_for([@school, @class]) do |f| %>
<%= f.label :name, "class title" %>
<%= f.text_field :name %>
<%= f.submit "Create class", class: "btn btn-large btn-primary" %>
<% end %>
</div>