它创建了对象,表示它已成功创建,但所有字段都以nil值保存在数据库中。仅正常保存created_at
和updated_at
。
我的controllers/admin/categories_controller.rb
def new
@admin_category = Category.new
end
# GET /admin/categories/1/edit
def edit
end
# POST /admin/categories
# POST /admin/categories.json
def create
@admin_category = Category.new(params[:category])
respond_to do |format|
if @admin_category.save
format.html { redirect_to admin_category_path(@admin_category), notice: 'Category was successfully created.' }
format.json { render :show, status: :created, location: admin_category_path(@admin_category) }
else
format.html { render :new }
format.json { render json: @admin_category.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /admin/categories/1
# PATCH/PUT /admin/categories/1.json
def update
respond_to do |format|
if @admin_category.update(admin_category_params)
format.html { redirect_to @admin_category, notice: 'Category was successfully updated.' }
format.json { render :show, status: :ok, location: @admin_category }
else
format.html { render :edit }
format.json { render json: @admin_category.errors, status: :unprocessable_entity }
end
end
end
这是我的型号/类别型号:
class Category < ActiveRecord::Base
belongs_to :category
end
这是我的routes.br文件
namespace :admin do
resources :categories
end
我的观点/ admin / categories / _form.html.erb
<%= form_for(@admin_category, url: admin_categories_path) do |f| %>
<% if @admin_category.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@admin_category.errors.count, "error") %> prohibited this admin_category from being saved:</h2>
<ul>
<% @admin_category.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :is_active %><br>
<%= f.check_box :is_active %>
</div>
<div class="field">
<%= f.label :main_menu %><br>
<%= f.check_box :main_menu %>
</div>
<div class="field">
<%= f.label :category_id %><br>
<%= f.number_field :category_id %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
当我尝试编辑时,我收到此错误:
No route matches [PATCH] "/admin/categories"
我是Ruby on Rails的新手,所以我会帮助你! 谢谢!
答案 0 :(得分:0)
您在创建新类别时只传递:category
:
def create
@admin_category = Category.new(params[:category])
将其更改为Category.new(user_params)
,然后重试。这将传递您正在创建的所有参数并将其提供给数据库。
此外,允许您尝试传递的参数:
def user_params
params.require(:admin_category).permit(:name, :is_active, :main_menu, :category_id)
end
答案 1 :(得分:0)
#app/controllers/categories_controller.rb
class CategoriesController < ApplicationController
def create
@admin_category = Category.new category_params
end
private
def category_params
params.require(:category).permit(:name, :is_active, :main_menu, :category_id)
end
end
-
作为提示,如果您使用带有表单的嵌套对象,则可以传递数组中的两个对象以创建嵌套路径:
#app/views/admin/categories/new.html.erb
<%= form_for [:admin, @admin_category] do |f| %>