Home > Enterprise >  retrieve current parameter value in Rails controller - Error: Couldn't find Question without an
retrieve current parameter value in Rails controller - Error: Couldn't find Question without an

Time:04-16

Upon clicking delete I want my page to redirect to the current user's poll. This something like this. questions_controller.rb:

  def destroy
    @poll_id = Question.find(param[:poll_id])
    @question.destroy

    respond_to do |format|
      format.html { redirect_to user_poll_url(current_user.id, @question.poll_id), notice: "Question was successfully destroyed." }
      format.json { head :no_content }
    end
  end

The Questions_controller's content is the same as the rails generated with the exception of the above change.

the question_controller has the poll_id as a paramter. How do I retrieve it's current value to use for redirection.

def question_params
  params.require(:question).permit(:poll_id, :title, :description)
end

routes.rb

  resources :users do
    resources :polls
  end
  resource :polls do
    resources :questions 
  end

The error i'm getting is:

ActiveRecord::RecordNotFound in QuestionsController#destroy
Couldn't find Question without an ID

Extracted source (around line #52):           
  # DELETE /questions/1 or /questions/1.json
  def destroy
    @poll_id = Question.find(param[:poll_id])
    session[:return_to] ||= request.referer
    @question.destroy

with line 52 being @poll_id = Question.find(param[:poll_id])

CodePudding user response:

param[:poll_id] is not correct. You always get these attributes in the controller in the method named params and as we submit a form from the front end Rails maps them to a specific key (name of the model singular), for example, to get the poll_id you need to use:

question_params[:poll_id]

which is equivalent to:

params[:question][:poll_id]

Also not sure if you poll_id would equal to the id saved in questions table. The find method would always find by id which means that:

Question.find(param[:poll_id])

means

SELECT * FROM questions WHERE id = param[:poll_id]

So if poll_id is equivalent to id then that is fine or you may want to replace find by find_by or you can also use params[:id] instead of poll_id if that exists (depends on your routes).

More information here on params: https://edgeguides.rubyonrails.org/action_controller_overview.html#parameters

  • Related