mGarsteck mGarsteck - 7 months ago 10
Ruby Question

param is missing or the value is empty: category

Im trying to create a new Category based on the title of the 'grow' that im creating (for a garden management tool'

But Im getting the following error:

'param is missing or the value is empty: category'

[edit] this is how the code is fixed. As per the suggestion in the comments:

remove the

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


and replace with
@grow = Grow.new(grow_params)


and in the Grow model add

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


and its fixed.

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


I simply want to pass in the grow.title to new category name
However im not sure how to implement it.

Answer

In your create method leave the statement to be @grow = Grow.new(grow_params)

and in your Grow model, write an after_create callback

within which you create your Category like Category.create(name: self.title)