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

时间:2009-09-20 11:58:17

标签: ruby-on-rails ruby database boolean

我想在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中实现相同的目标?

只是为了澄清,假设我有一个带有“红色”,“蓝色”,“黑色”,“白色”复选框的表单。用户可以选择无,一个或多个值。如何存储和检索这组值?

BTW,另一种在delphi中执行此操作的方法是使用按位数学:

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

可以存储和检索为整数

4 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

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

对所有标志使用一个整数,具有db搜索和范围。

答案 3 :(得分:0)

也许你会发现这更容易

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]]