Решение проблемы
Когда я хочу отредактировать существующий раздел, появляется ошибка:
"Не удалось найти категорию с'id '="
И моя страница перенаправляется на "http://localhost:3000/sections/1", когда она должна быть перенаправлена на" http://localhost:3000/categories/3/sections/1/".
sections_controller.rb
class SectionsController < ApplicationController
before_action :find_the_category
def index
@sections = @category.sections
end
def show
@section = @category.sections.find(params[:id])
end
def new
@section = Section.new
end
def edit
@section = @category.sections.find(params[:id])
end
def create
@section = @category.section.create(section_params)
flash[:success] = "Section ajouté avec succés"
if @section.save
redirect_to category_section_path(@category, @section)
end
end
def update
flash[:success] = "Section modifié avec succés"
@section = @category.sections.find(params[:id])
@section.update(section_params)
redirect_to category_section_path(@category, @section)
end
def destroy
flash[:danger] = "Section supprimé"
@section = Section.find(params[:id])
@section.destroy
redirect_to category_sections_path
end
private
def find_the_category
@category = Category.find(params[:category_id])
end
def section_params
params.require(:section).permit(:title, :content)
end
end
routes.rb
Rails.application.routes.draw do
resources :categories do
resources :sections
end
end
раздел # _form.html.erb
<%= bootstrap_form_for([@category, @section]) do |f| %>
<% if @section.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@section.errors.count, "error") %> prohibited this reponse from being saved:</h2>
<ul>
<% @section.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :Titre %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :Description %><br>
<%= f.text_area :content %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
category.rb
class Category < ActiveRecord::Base
# une catégorie peut avoir plusieurs questions relations has-many
has_many :questions
has_many :sections
end
section.rb
class Section < ApplicationRecord
belongs_to :category
end