param缺失或值为空:category

时间:2016-04-27 22:34:19

标签: ruby ruby-on-rails-4

我试图根据“成长”的标题创建一个新的类别。我正在创建(用于花园管理工具'

但我收到以下错误:

' param丢失或值为空:category'

[编辑]这是代码修复的方式。根据评论中的建议:

删除@grow = Grow.new(grow_params.merge(category: Category.create(cat_params)))

并替换为@grow = Grow.new(grow_params)

并在Grow模型中添加

after_create do Category.create(name: self.title) end

及其固定。

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

我只是想将grow.title传递给新的类别名称 但是我不确定如何实现它。

1 个答案:

答案 0 :(得分:2)

在您的create方法中留下声明 @grow = Grow.new(grow_params)

并在您的Grow模型中,撰写after_create回调

您可以在其中创建Category Category.create(name: self.title)