views:

38

answers:

1

Hi.

I've got form for some model A, which has got few fields:

  • tile
  • description
  • ...
  • colors

colors are selected from multiple select and options are ['red', 'green', 'blue', 'yellow']. User can choose colors as many as he wants. I don't think that making Color model and has_many relationship is good solution here to store colors data in model A. So question is:

How to store multiple data in db for such multiple select forms?

+1  A: 

If you have limited number of colors, then you can store it as a string: "rby" means that user selected red, blue and yellow. Of course you can use any character to represent any color. In this solution you can easily store about 30-40 colors (what probably is enough). You can also store them as comma separeted words: "red, blue, yellow" and when you fetch it in Rails, just do @a.colors.split(',') and you will get array of names of colors.

Although if you want to store it as a string, it requires from you to write some more code in controllers to translate colors field to checkboxes and in the other side.

klew
That is the way I am working now. Kind of csv, :attr_accessor and few extra methods in model. But now I try to understand if there any another solution using serialization or some other exotic stuff. Anyway, thanks for feedback :)
fl00r