问题解决 当我要编辑现有部分时,出现错误:
“找不到带有'id'=”
的类别
当我的页面应重定向到“ http://localhost:3000/sections/1 categories / 3 / sections / 1 /”时,页面也重定向到“ http://localhost:3000/”。
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
section#_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
答案 0 :(得分:1)
在浏览器中检查您的表单网址,我认为这是错误的。
您没有为bootstrap_form_for助手提供任何类别,因此它可能会生成错误的链接。
您的表单模板必须像这样:
bootstrap_form_for([@category, @section])