使用Rails 3的嵌套资源来正确关联模型

时间:2013-01-09 04:05:36

标签: ruby-on-rails ruby-on-rails-3 rails-routing

我正在努力更好地处理Rail的嵌套资源,并使用模型学校 Class 制作了一个测试应用。在我的routes.rb文件中,我有:

resources :schools do
   resources :classes
end

学校班级的以下模型关系:

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这样的辅助方法,它可以占用包含school_id的URI的前半部分,以允许我在控制器中编写函数,如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>

1 个答案:

答案 0 :(得分:1)

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

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