我有一个Rails应用程序,并且正在使用jQuery在后台查询我的搜索视图。有字段q
(搜索词)、start_date
、end_date
和internal
。internal
字段是一个复选框,我正在使用is(:checked)
方法来构建要查询的url:
$.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”,我需要将其转换为布尔值。我当然可以这样做:
def to_boolean(str)
return true if str=="true"
return false if str=="false"
return nil
end
但我认为一定有一种更Ruby的方式来解决这个问题!是不是有...?
发布于 2015-05-01 04:09:53
ActiveRecord::Type::Boolean.new.type_cast_from_user
根据Rails的内部映射ConnectionAdapters::Column::TRUE_VALUES
和ConnectionAdapters::Column::FALSE_VALUES
执行此操作
[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_bool
或to_boolean
)方法,如下所示:
class String
def to_b
ActiveRecord::Type::Boolean.new.type_cast_from_user(self)
end
end
https://stackoverflow.com/questions/8119970
复制相似问题