首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将字符串"true“和"false”转换为布尔值

将字符串"true“和"false”转换为布尔值
EN

Stack Overflow用户
提问于 2011-11-14 18:06:38
回答 12查看 120.8K关注 0票数 86

我有一个Rails应用程序,并且正在使用jQuery在后台查询我的搜索视图。有字段q (搜索词)、start_dateend_dateinternalinternal字段是一个复选框,我正在使用is(:checked)方法来构建要查询的url:

代码语言:javascript
运行
复制
$.getScript(document.URL + "?q=" + $("#search_q").val() + "&start_date=" + $("#search_start_date").val() + "&end_date=" + $("#search_end_date").val() + "&internal=" + $("#search_internal").is(':checked'));

现在我的问题出现在params[:internal]中,因为有一个字符串包含"true“或"false”,我需要将其转换为布尔值。我当然可以这样做:

代码语言:javascript
运行
复制
def to_boolean(str)
     return true if str=="true"
     return false if str=="false"
     return nil
end

但我认为一定有一种更Ruby的方式来解决这个问题!是不是有...?

EN

Stack Overflow用户

发布于 2015-05-01 04:09:53

ActiveRecord::Type::Boolean.new.type_cast_from_user根据Rails的内部映射ConnectionAdapters::Column::TRUE_VALUESConnectionAdapters::Column::FALSE_VALUES执行此操作

代码语言:javascript
运行
复制
[3] pry(main)> ActiveRecord::Type::Boolean.new.type_cast_from_user("true")
=> true
[4] pry(main)> ActiveRecord::Type::Boolean.new.type_cast_from_user("false")
=> false
[5] pry(main)> ActiveRecord::Type::Boolean.new.type_cast_from_user("T")
=> true
[6] pry(main)> ActiveRecord::Type::Boolean.new.type_cast_from_user("F")
=> false
[7] pry(main)> ActiveRecord::Type::Boolean.new.type_cast_from_user("yes")
DEPRECATION WARNING: You attempted to assign a value which is not explicitly `true` or `false` ("yes") to a boolean column. Currently this value casts to `false`. This will change to match Ruby's semantics, and will cast to `true` in Rails 5. If you would like to maintain the current behavior, you should explicitly handle the values you would like cast to `false`. (called from <main> at (pry):7)
=> false
[8] pry(main)> ActiveRecord::Type::Boolean.new.type_cast_from_user("no")
DEPRECATION WARNING: You attempted to assign a value which is not explicitly `true` or `false` ("no") to a boolean column. Currently this value casts to `false`. This will change to match Ruby's semantics, and will cast to `true` in Rails 5. If you would like to maintain the current behavior, you should explicitly handle the values you would like cast to `false`. (called from <main> at (pry):8)
=> false

因此,您可以在初始化器中创建自己的to_b (或to_boolto_boolean)方法,如下所示:

代码语言:javascript
运行
复制
class String
  def to_b
    ActiveRecord::Type::Boolean.new.type_cast_from_user(self)
  end
end
票数 8
EN
查看全部 12 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8119970

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档