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
のような URL で作成された投稿に を関連付けるのに苦労しています/schools/1/posts/new
。より正確には、current_school
が含まれる URI の前半を取得できるようなヘルパー メソッドを定義して、 = に関連するすべての投稿を自動的にプルschool_id
するような関数をコントローラーに記述できるようにしたいと考えています。 URL。ありがとう!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>