AnthonyGalli.com AnthonyGalli.com - 6 months ago 8
Ruby Question

if params[:attribute] == true then do "X" in controller?

How to trigger

#x
condition if
:someday
is equal to
true
?

db

t.boolean "someday"


controller

# In new.html.erb user inputs challenge.name and can checkmark challenge.someday
def new
@challenge = Challenge.new
end

# If user checkmarks someday than do x otherwise do y (keep in mind conditional is triggered before challenge is created)
def create
if params[:someday] == true
#x
else
#y
end
end


console

Started POST "/challenges" for 127.0.0.1 at 2016-06-03 14:04:01 -0400
Processing by ChallengesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Ii3RdJYAnOpT/OOkqVA74b8YD5suUA3Rf4Wegih65xSSU0r1c5DB0UCJVWcGcid3JtSt6fjzmfYpbWZtf2Dm/A==", "challenge"=>{"someday"=>"1", "name"=>"test"}, "button"=>""}
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 15]]
Rendered shared/_error_messages.html.erb (0.2ms)
Rendered challenges/create.html.erb within layouts/application (48.5ms)


Right now no matter how I've tweaked
params[:someday] == true
the
#y
condition keeps getting triggered. I've tried,
params[:someday] == "true"
,
params[:someday] == 1
,
params[:someday] == "1"
,
params[:someday] == "t"

Answer

You are doing it wrong. You should do params[:challenge][:someday] as the someday is inside the challenge hash. The below code should work

def create
  if params[:challenge][:someday] == "1"
    #x
  else
    #y
  end
end