I have a session variable (user_id) that I'd like to include as a foreign key on a record the user is inserting. I have the form values all coming through the form submit to my controller's entity.update(params) method without a problem using the default params definition. That code looks like
def brand_params
@brand_params = params.require(:brand).permit(:name, :brand_type, :profile_id)
end
The update method looks like
if @brand.update(brand_params)
format.html { redirect_to @brand, notice: 'Widget was successfully updated.' }
format.json { render :show, status: :ok, location: @brand }
else
format.html { render :edit }
format.json { render json: @brand.errors, status: :unprocessable_entity }
end
Now I'd like to append the :profile_id session variable to the @brand_params and following other threads here, I've tried a setter method:
def set_brand_params(key, val)
if @brand_params != nil
@brand_params[key] = val
end
end
However, calling this, @brand_params is always nil. Trying to directly add to the brand_params hash doesn't work because it's a better method. If there's a better way to meet this (I'd assume common) use case, I'm all ears! Otherwise, I'd like to know why the var is always nil though in this context, at least the brand_params method sees it as defined and with value. I got this solution in Adding a value to ActionController::Parameters on the server side
Here is the update method as requested:
def update
puts "update"
set_brand_params("profile_id", session[:prof])
respond_to do |format|
if @brand.update(brand_params)
format.html { redirect_to @brand, notice: 'Widget was successfully updated.' }
format.json { render :show, status: :ok, location: @brand }
else
format.html { render :edit }
format.json { render json: @brand.errors, status: :unprocessable_entity }
end
end
end
set_brand_parmasbefore any call ofbrand_paramsyes, @brand_params is undefined (nil).