2

I have a User with one or more email addresses, and I don't want to create a new table for emails. The idea was to store email addresses as Array, but how do I implement this in the controller and the model? This is the controller

class UsersController < ApplicationController
def update
@user =User.find(params[:id])

if @user.update_attributes(user_params)
  redirect_to :action => 'show', :id => @user

Is it possible to check during update if the email parameter is already there or a new one and if it is new add it to an Array? I don't know if I made myself clear, but thanks anyway for any answer you or suggestion you will provide! By the way, I am using mysql and I can't switch to a different one!

1 Answer 1

6

you can store it as a comma separated list.

or use rails serialize to do the job

For example,

class User < ActiveRecord::Base 
    serialize :emails, Array 
end

would maintain the array format when retrieved as user.emails. you can always validate whether an email is present in an array.

But my suggestion is to have a separate model. Future might hold new features like assigning primary and secondary emails and what not. then this design would not be so helpful

Sign up to request clarification or add additional context in comments.

5 Comments

P.S - Any class type can be passed on to the serialize directive. Array, Hash, JSON another activerecord too possibly
Thank you very much! I am actually using active_model_serializer to render data as Json for an Ember Client. Do you think I can do the same thing through active_model_serializer? Thank you again for you answer!
From what I read about active_model_serializer from railscasts.com/episodes/409-active-model-serializers, it seems to be more of a representational utility (convert ActiveRecord to json and hence create an API). but here, our goal is to store object in a serialized fashion. I think this will not serve the purpose. Its understandable to want to use one fix for all :) Been there! P.S - rails serialize is part of rails already and so you don't have to feel like using unwanted extra gem or something. Its there for us developers to exploit.
Thank you very much my friend! You've been very helpful! I will follow your suggestions and eventually I'll let you know the results! Have a nice day!
This answer solves our problems, but how do we query array items. In this example (emails): assume we have ['[email protected]','[email protected]']. how do we query users that have '[email protected]'? how do we query users that have 'blah.com' emails?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.