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



我试图更好地处理铁路的嵌套资源,并制作了一个测试应用程序与模型学校。在我的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 

我很难得到与/schools/1/posts/new这样的URL下创建的帖子相关联的school_id。更准确地说,我想定义一个像current_school这样的助手方法,它可以采用包含school_id的URI的前半部分,以允许我在控制器中编写函数,如current_school.posts.all,它将自动提取与school_id = URL中的内容相关的所有帖子。谢谢!

* 编辑

以下是我在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>

嵌套资源时,可以免费获得几个帮助器方法,如下所述。您正在寻找的方法可以写成:

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

相关内容

  • 没有找到相关文章

最新更新