When a has_many
association basically serves to store a list of associated strings (tags, categories, ...), it can be convenient to represent this association as a string array in the containing model. Here is an example for this pattern from the
acts-as-taggable-on
Show archive.org snapshot
gem:
post = Post.last
p post.tag_list # ['foo', 'bar', 'baz']
post.tag_list = ['bam']
p post.tag_list # ['bam']
This string array tag_list
is magical in several ways:
has_many
associationUse the attached Modularity Show archive.org snapshot below to add such a magical array to your model. Besides using the trait, you will need to implement two methods to synchronize the string array with its underlying association:
class Note < ActiveRecord::Base
include DoesListField[:topic_list]
private
def read_topic_list
topics.collect(&:name)
end
def write_topic_list(list)
topics.delete_all
for name in list
topics.create!(:name => name)
end
end
end
In case your list holds integer values, you might want to use the :integer
option so elements get casted to numbers automagically:
class Note < ActiveRecord::Base
include DoesListField[:author_list, integer: true]
end