Rails ActionController::ParameterMissing in Questi

2019-09-05 03:50发布

问题:

I am trying to create a boolean toggle button to change a value in my model Question. I am just learning rails so bear with me.

In my view I created a button:

<%= link_to("Answered", question_path(question, :status => true), :method => :put) %>

when I look at the URL for the button it is :

hackerQ.com/questions/8?status=true

This is the Error I am given.

Rails ActionController::ParameterMissing in QuestionsController#update

  # Never trust parameters from the scary internet, only allow the white list through.
    def question_params
      params.require(:question).permit(:topic, :question, :status, :user_id, :teacher_id)
    end
end

My Question is should have have created a new action in my questions controller or added something to my params.require?

回答1:

Your controller is looking for the :question parameter, but it cannot find it anywhere. You are not referencing :question anywhere, i think you have an error in the question_path() call. Try:

<%= link_to("Answered", question_path(:question, :status => true), :method => :put) %>


回答2:

Because of the code:

params.require(:question)

your params hash has to have a "question" key, like this:

{"question" => {"status"=>"true"}` ...} 

I don't know the proper way to get that. Maybe in link_to do:

link_to("Answered", question_path(question, "question[status]" => true), :method => :put)

Also, link_to creates an <a> tag. Why are you calling that a button? In html, a button and a link are different things.



回答3:

No, you should have in your app something like this:

<%= form_for(question, method: :put) do |f| %>
  <% f.hidden_field :status, value: true %>
  <% f.submit "Answered" %>
<% end %>

I don't know if this is the right syntax, but you can't send those parameters over the URL.



回答4:

A good way to debug is to print all the params you are passing to your controller from the view. You can do that by adding the following piece in your html.erb file(view):

<%= params.inspect %>

Or to print the value of the param your controller is expecting, use:

<%= params[:question] %>

where question is the name of the param you are expecting.

That will give you a clear picture of what you are passing or failing to pass.