代码之家  ›  专栏  ›  技术社区  ›  Mike Sutton

在Ruby和Rails中存储布尔值的数组或散列

  •  0
  • Mike Sutton  · 技术社区  · 16 年前

    我想用Ruby创建一组值,我可以在Rails下的MySQL数据库中存储和检索这些值。

    在Delphi中,我将使用:

    //Create an enumeration with four possible values
    type TColour = (clRed, clBue, clBlack, clWhite);
    //Create a set which can hold values from the above enumeration
         TColours = set of TColours;
    //Create a variable to hold the set
    var MyColours = TColours;
    begin
      //Set the variable to hold two values from the enumeration
      MyColours = [clRed, clBlack];
      //MyColours now contains clRed and clBlack, but not clBlue or clWhite
    
      //Use a typecast to convert MyColours to an integer and store it in the database
      StoreInDatabase(Integer(MyColours));
    
      //Typecast the Integer back to a set to retrieve it from the database
      MyColours := TColours(RetrieveFromDatabase);
    end;
    

    如何在Ruby/Rails中实现同样的功能?

    为了澄清,假设我有一个表格,上面有“红色”、“蓝色”、“黑色”、“白色”复选框。用户可以选择无、一个或多个值。如何存储和检索该组值?

    顺便说一句,在delphi中实现这一点的另一种方法是使用位数学:

    const
      Red = 1;
      Blue = 2;
      Black = 4;
      White = 8;
    var MyColours: Integer;
    begin
      MyColours := Red+Black; //(or MyColours = Red or Black)
    

    4 回复  |  直到 15 年前
        1
  •  3
  •   khelll    16 年前

    以下是按位解决方案的简单实现:

    module Colors
      Red = 1
      Blue = 2
      Black = 4
      White = 8
      ColorsSet = [Red,Blue,Black,White]
    
      # Mixing valid colors
      def self.mix(*colors) 
        colors.inject{|sum,color| ColorsSet.include?(color) ? color | sum : sum }
      end
    
      # Get an array of elements forming a mix
      def self.elements(mix)
        ColorsSet.select{|color| color & mix > 0}
      end
    end
    
    mix = Colors::mix(Colors::Red,Colors::Blue)
    
    puts mix #=> 3
    
    puts Colors::elements(mix) 
    #=> 1
    #   2
    
        2
  •  1
  •   rnicholson    16 年前

    根据评论和修改后的问题,听起来你想试试 Enum Column plugin for Rails . 有一个助手,enum_radio(),在您的表单中可能很有用。

        3
  •  1
  •   Peter H. Boling    12 年前

    使用漂亮的宝石: https://github.com/pboling/flag_shih_tzu

    对所有标志、has db search和作用域使用一个整数。

        4
  •  0
  •   Jonas Elfström    15 年前

    Colors={:red=>1, :blue=>2, :black=>4, :white=>8}
    mix = Colors[:blue] + Colors[:black]
    Colors.select{|key,value| value & mix > 0}
    => [[:blue, 2], [:black, 4]]