AnthonyGalli.com AnthonyGalli.com - 4 months ago 14
Ruby Question

param is missing or the value is empty?

ActionController::ParameterMissing in DuelersController#update
param is missing or the value is empty: dueler


How can I fix the error so that when a user clicks "Accept" or "Decline" it will change the value of
:accept


Dueler.last
id: 20,
user_id: 78,
challenge_id: 178,
duel_id: 13,
accept: nil>


form

<%= form_for @dueler do |f| %>
<%= f.button "Accept", name: "button_action", value: "accept" %>
<%= f.button "Decline", name: "button_action", value: "decline" %>
<% end %>


duelers_controller.rb

def update
if params['button_action'] == 'accept'
@dueler.accept = 1
else
@dueler.accept = 0
end
@dueler.update(dueler_params)
redirect_to :back
end

def dueler_params
params.require(:dueler).permit(:id, :duel_id, :user_id, :challenge_id, :accept)
end


terminal

Processing by DuelersController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"zn6Z9XuCQ2JahhtrZzFpEl3ENe+bcmOdDH/gz6VZ4p0mnRvgwpixdF2uA/sFgaQZFu2dEKR0DivQpJLqu96pxg==", "button_action"=>"accept", "id"=>"15"}


This is how the parameters look like when I submit with
:accept
as a
check_mark
, which doesn't raise any error:

Processing by DuelersController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"KWDac1I2rNRZd6oeCan0F7qlNY4c5K5vd6U988MJ6n3Bg1hm6yxewl5fso5rGTkc8YydcSPiw9mrfk/W3Y6hJg==", "dueler"=>{"accept"=>"1"}, "commit"=>"Update Dueler", "id"=>"15"}

Answer

Quick fix option 1:

<%= form_for @dueler do |f| %> <%= f.button "Accept", name: "dueler[button_action]", value: "accept" %> <%= f.button "Decline", name: "dueler[button_action]", value: "decline" %> <% end %>

Quick fix option 2:

def dueler_params params.permit(:id, :duel_id, :user_id, :challenge_id, :button_action) end

Option 3 - bigger changes, but I like it best

form

<%= form_for @dueler do |f| %> <%= f.button "Accept", name: "dueler[accept]", value: 1 %> <%= f.button "Decline", name: "dueler[accept]", value: 0 %> <% end %>

duelers_controller.rb

def update @dueler.update(dueler_params.merge(accept: dueler_params[:accept].to_i)) redirect_to :back end

Either option should get you past this particular error. However, I worry that you're not fully understanding how pieces of your code work together. I expect the next part of your controller to behave differently than you'll expect:

if params['button_action'] == 'accept' @dueler.accept = 1 else @dueler.accept = 0 # "accept" sounds like a Boolean piece of data to me, but it looks like you're saving it as an integer end @dueler.update(dueler_params) # I expect you'll get "undefined method `button_action=' for #<Dueler:0x007fc4fac732d0>" here

You may want to play with form_for and Strong Parameters a bit more to understand how arguments you pass to button and such turn into HTML, which then turn into params, and how they're handled in the controller.