Reputation: 3
What is the best way/practice to declare a Rails(4) array field (with mysql database)? I need to store some ids into that array. I tried to do this using the ActiveRecord Serializer and I customized the attribute accessors so my field can behave like an array.
class OfficeIds < ActiveRecord::Base
serialize :office_ids
def office_ids=(ids)
ids = ids.join(",") if ids.is_a?(Array)
write_attribute(:office_ids, ids)
end
def office_ids
(read_attribute(:office_ids) || "").split(",")
end
end
I feel that this is not the best approach for this kind of situation. Any help would be appreciated. Thanks!
Upvotes: 0
Views: 81
Reputation: 211670
If you're using the serializer, there's no need to write a wrapper method for this. You should be able to assign arbitrary objects to that field:
ids = OfficeIds.new
ids.office_ids = [ 1, 2, 3 ]
ids.save
It is rather odd to have a model called OfficeIds
though, as a plural name for this willc cause all kinds of trouble. Are you sure you don't want a traditional has_many
relationship for these?
Upvotes: 2