How to show a serialized Array attribute for a Rails ActiveRecord Model in a form?
forms, ruby-on-rails
Solution
If you want multi-select HTML field, try:
= form_for @user do |f|
= f.select :favorite_colors, %w[full colors list], {}, :multiple => true
If you're using simple_form gem, you can present the options as check boxes easily:
= simple_form_for @user do |f|
= f.input :favorite_colors, as: :check_boxes, collection: %w[full colors list]
Problem
We're using the "serialize" feature of ActiveRecord in Rails like this: ``` class User < ActiveRecord::Base serialize :favorite_colors, Array .... end ``` So we can have ``` u = User.last u.favorite_colors = [ 'blue', 'red', 'grey' ] u.save! ``` So basically ActiveRecord is serializing the array above and stores it in one database field called favorite_colors. My question is: How do you allow a user to enter his favorite colors in a form? Do you use a series of textfields? And once they're entered, how do you show them in a form for him to edit? This is a question related to Rails Form Helpers for serialized array attribute. Thanks