如何在 Rails 中提交布尔参数? [英] How do I submit a boolean parameter in Rails?
问题描述
我正在提交一个值为 true
的参数 show_all
.此值与模型无关.
I'm submitting a parameter show_all
with the value true
. This value isn't associated with a model.
我的控制器正在将此参数分配给一个实例变量:
My controller is assigning this parameter to an instance variable:
@show_all = params[:show_all]
但是,@show_all.is_a?String
和 if @show_all == true
总是失败.
However, @show_all.is_a? String
, and if @show_all == true
always fails.
Rails 将哪些值解析为布尔值?如何明确指定我的参数是布尔值,而不是字符串?
What values does Rails parse as booleans? How can I explicitly specify that my parameter is a boolean, and not a string?
推荐答案
我想对 zetetic 的答案发表评论,但由于我不能这样做,所以我将其作为答案发布.
I wanted to comment on zetetic answer but as I can't do that yet I'll post this as an answer.
如果你使用
@show_all = params[:show_all] == "1"
那么你可以删除 吗?true : false
因为 params[:show_all] == "1"
语句本身将评估为 true 或 false,因此不需要三元运算符.
then you can drop ? true : false
because params[:show_all] == "1"
statement itself will evaluate to true or false and thus ternary operator is not needed.
这篇关于如何在 Rails 中提交布尔参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!