How to check if a param is true or false?

前端 未结 4 725
我寻月下人不归
我寻月下人不归 2020-12-24 12:10

This is really racking my brain, but maybe I\'m trying to hard.

I\'m passing a param via a URL (example.com?debug=true)

So I basically want to say:



        
相关标签:
4条回答
  • 2020-12-24 12:49

    Since Rails/ActiveRecord 4.2.0 it is

    if ActiveRecord::Type::Boolean.new.type_cast_from_user params[:debug]
      do xyz
    else
      do abc
    end
    

    In Rails 5 it is:

    if ActiveModel::Type::Boolean.new.cast params[:debug]
      do xyz
    else
      do abc
    end
    
    0 讨论(0)
  • 2020-12-24 12:52

    params come in as strings, so you need to compare against "true", not true.

    0 讨论(0)
  • 2020-12-24 12:57

    You could use ActiveRecord's method of checking truthful values if you don't want to reinvent the wheel (this is what is used when passing params inside an ActiveRecord object

    Rails 3-4.1

    if ActiveRecord::ConnectionAdapters::Column.value_to_boolean(params[:debug])
        do xyz
    else
        do abc
    

    Rails 4.2.0

    ActiveRecord::Type::Boolean.new.type_cast_from_database(params[:debug])
    

    Rails 5

    ActiveModel::Type::Boolean.new.cast(params[:debug])
    

    Might be worth wrapping in a helper but never the less it's quite flexible:

    rails c
    Loading development environment (Rails 3.2.6)
    1.9.3p194 :001 > ActiveRecord::ConnectionAdapters::Column.value_to_boolean '1'
     => true 
    1.9.3p194 :002 > ActiveRecord::ConnectionAdapters::Column.value_to_boolean '0'
     => false 
    1.9.3p194 :003 > ActiveRecord::ConnectionAdapters::Column.value_to_boolean 1
     => true 
    1.9.3p194 :004 > ActiveRecord::ConnectionAdapters::Column.value_to_boolean true
     => true 
    1.9.3p194 :005 > ActiveRecord::ConnectionAdapters::Column.value_to_boolean 'true'
     => true 
    1.9.3p194 :006 > ActiveRecord::ConnectionAdapters::Column.value_to_boolean 'on'
     => true 
    1.9.3p194 :007 > ActiveRecord::ConnectionAdapters::Column.value_to_boolean 'off'
    

    Custom extension

    Some people frown on extending core classes but this does fit with the DRY principle.

    # config/initializer/boolean.rb
    class Boolean
      def self.parse(value)
        ActiveRecord::ConnectionAdapters::Column.value_to_boolean(value)
      end
    end
    

    Then used like

    if Boolean.parse(params[:debug])
      then xyz
    
    0 讨论(0)
  • 2020-12-24 12:57

    But for whatever reason that if statement just isn't doing like it seems like it should.

    I can almost guarantee that it is doing exactly what it should. When things don't make sense, one of our assumptions is wrong.

    Is the value actually a boolean or is it string (or something else?). If the value is a string then of course the comparison to the boolean value true will fail. Try comparing to 'true' and see if that works.

    0 讨论(0)
提交回复
热议问题