如果#x
等于:someday
,如何触发true
条件?
分贝
t.boolean "someday"
控制器
# 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
控制台
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)
现在无论我如何调整params[:someday] == true
,#y
条件都会被触发。我已经尝试过,params[:someday] == "true"
,params[:someday] == 1
,params[:someday] == "1"
,params[:someday] == "t"
答案 0 :(得分:2)
你做错了。您应该params[:challenge][:someday]
,因为someday
位于challenge
哈希中。以下代码应该可以使用
def create
if params[:challenge][:someday] == "1"
#x
else
#y
end
end
答案 1 :(得分:0)
params[:someday]
应为params[:challenge][:someday]
,因为您提交的值来自表单
def create
if params[:challenge][:someday]
#x
else
#y
end
end
会做的伎俩
答案 2 :(得分:0)
你的check_box
在html中返回1
,如果你想要它返回布尔值,那么就像下面这样做。另外,在控制器中,params应该是这样的:params[: challenge][:someday]
<强>形式强>
<%= f.check_box :someday, {}, true , false %>
<强>控制器强>
def create
if params[: challenge][:someday]
#x
else
#y
end
end