开发者

Many Booleans On Two Tables

开发者 https://www.devze.com 2023-04-09 21:14 出处:网络
Using Rails 2.1 and Mysql. I have a corporation model, which has_many companies And of course the company model, which belongs_to corporation

Using Rails 2.1 and Mysql.

I have a corporation model, which has_many companies

And of course the company model, which belongs_to corporation

I need to add quite a few boolean columns to these two tables, but this feels really wrong. Each table will have the same booleans, and we would be checking first the company to see if it's true, and then corporation. So, the options I can see are these:

  • Add the boolean values to each table. I suppose this is simplest but feels really redundant.

  • Create an extra table called something like "boolean_options", which would belong_to company and corporation. Each boolean is added to this table, and then connect to the开发者_StackOverflow中文版 appropriate model(s).

  • Use something like the has_many_booleans gem, which means I add one column (boolean) to each table and handle the data in my code. This seems like it would be the least obvious solution, but feels more elegant to me, especially when it comes time to add more booleans to these tables.

What is the best way to handle booleans that will appear across multiple tables?


The answer may depend more on your overall concept than anything else. For each true/false bit of data, ask yourself how closely linked it is to the essence of the model. How often will each bit be referenced in model instances, or used in searches. Those that are closely linked may belong in the model; the ones that are less so may be better grouped in other tables.

Example: In the real world, a corporation is a type of company and shares many of the Company attributes; these attributes could be stored in the Company table, perhaps with an is_a_corporation flag.

Where corporations have unique attributes, such as the ability to own companies, these functions and attributes should be in the Corporation model.

Booleans as Bits: I don't think there is anything wrong with having many boolean attributes in a model, but I agree that it seems inelegant to have all those boolean columns in the table. I checked out the has_many_booleans gem, which does offer some interesting opportunities for simulating bitwise operations and masks which, coming from the world of embedded software, makes a lot of sense to me.

Checking around, I discovered that Postgresql (my db of choice) offers the bitstring datatype and provides a plethora of actual bitwise operations on as many bits as you want, using just one column for all your booleans, which seems incredibly cool to me. The downside is you'd have to configure the column and and perform the operations in native SQL.

0

精彩评论

暂无评论...
验证码 换一张
取 消