Saving multiple select form data in db
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 c开发者_如何学运维an 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?
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.
 加载中,请稍侯......
      
精彩评论