Ruby 缺少参数或值为空:类别
我正在尝试根据我创建的“成长”标题创建一个新类别(用于花园管理工具) 但是我得到了以下错误: '参数丢失或值为空:类别' [编辑]这是代码的固定方式。根据评论中的建议: 删除Ruby 缺少参数或值为空:类别,ruby,ruby-on-rails-4,Ruby,Ruby On Rails 4,我正在尝试根据我创建的“成长”标题创建一个新类别(用于花园管理工具) 但是我得到了以下错误: '参数丢失或值为空:类别' [编辑]这是代码的固定方式。根据评论中的建议: 删除@grow=grow.new(grow\u-params.merge(category:category.create(cat\u-params))) 并替换为@grow=grow.new(grow\u参数) 在Grow模型中添加 在创建do之后 Category.create(名称:self.title) 结束 它是固定的
@grow=grow.new(grow\u-params.merge(category:category.create(cat\u-params)))
并替换为@grow=grow.new(grow\u参数)
在Grow模型中添加
在创建do之后
Category.create(名称:self.title)
结束
它是固定的
class GrowsController < ApplicationController
before_action :set_grow, only: [:show, :edit, :update, :destroy]
def index
@grows = Grow.all
end
def show
end
def new
@grow = Grow.new
end
def edit
end
def create
@grow = Grow.new(grow_params.merge(category: Category.create(cat_params)))
respond_to do |format|
if @grow.save
format.html { redirect_to @grow, notice: 'Grow was successfully created.' }
format.json { render :show, status: :created, location: @grow }
else
format.html { render :new }
format.json { render json: @grow.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /grows/1
# PATCH/PUT /grows/1.json
def update
respond_to do |format|
if @grow.update(grow_params)
format.html { redirect_to @grow, notice: 'Grow was successfully updated.' }
format.json { render :show, status: :ok, location: @grow }
else
format.html { render :edit }
format.json { render json: @grow.errors, status: :unprocessable_entity }
end
end
end
# DELETE /grows/1
# DELETE /grows/1.json
def destroy
@grow.destroy
respond_to do |format|
format.html { redirect_to grows_url, notice: 'Grow was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_grow
@grow = Grow.find(params[:id])
end
def cat_params
params.require(:category).permit(:name)
end
def grow_params
params.require(:grow).permit(:title, :notes, :category_id)
end
end
class GrowsController
我只想将grow.title传递给新的类别名称
但是,我不知道如何实现它。在您的
create
方法中,保留语句
@grow=grow.new(grow\u参数)
在您的Grow
模型中,在创建回调后编写
您可以在其中创建您的类别
像类别.create(名称:self.title)
在您的创建
方法中保留该语句
@grow=grow.new(grow\u参数)
在您的Grow
模型中,在创建回调后编写
在其中创建您的类别
就像类别。create(name:self.title)
谢谢,这很好地解决了问题。如果我想在删除grow时销毁类别,我会在销毁后使用相同的参数吗?-Category.destroy(name:self.title)好的,你可以这样做。但是我更喜欢使用dependent::destroy
作为你的关联。谢谢,这很好地解决了问题。如果我想在删除grow时销毁该类别,我会在销毁后使用相同的参数吗?-category.destroy(名称:self.title)好的,你可以这样做。但是我更喜欢使用dependent::destroy
来进行关联。