1

我试图更好地处理 Rail 的嵌套资源,并使用模型SchoolClass制作了一个测试应用程序。在我的routes.rb文件中,我有:

resources :schools do
   resources :classes
end

SchoolClass具有以下模型关系:

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>
4

1 回答 1

1

当您嵌套资源时,您可以免费获得几个帮助方法,如此所述。您正在寻找的方法将被写为以下之一:

new_school_class_path(@school)
new_school_class_path(@school_id)

虽然您的课程索引页面将是:

school_classes_path(@school)
school_classes_path(@school_id)

在您的 ClassesController 中,您将执行以下操作:

def index
  @classes = current_school.classes
end

def new
  @class = current_school.classes.build
end

private
def current_school
  @current_school ||= School.find(params[:school_id])
end
于 2013-01-09T04:10:07.163 回答