I am trying to get a better handle on Rail’s nested resources, and made a test app with models School and Class. In my routes.rb file, I have:
resources :schools do
resources :classes
end
With the following models relationship for School and Class:
class School < ActiveRecord::Base
attr_accessible: name
has_many :classes
end
and
class Class < ActiveRecord::Base
attr_accessible: name, school_id
belongs_to :school
end
I am having difficulty getting the school_id associated with the posts created under an URL like /schools/1/posts/new. More precisely, I would like to define a helper method like current_school that could take the first half of the URI where it contains the school_id, to allow me to write functions in the controller like current_school.posts.all that will automatically pull all the posts associated with school_id = what is in the URL. Thanks!
*Edit
Here is what I have in 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
And in the new.html.erb file:
<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>
When you nest your resources, you get several helper methods for free as explained here. The method you’re looking for would be written as one of:
While your classes index page would be:
In your ClassesController, you would do something like: