Rails数组和Mysql [英] Rails Arrays and Mysql

查看:108
本文介绍了Rails数组和Mysql的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有一个或多个电子邮件地址的用户,并且我不想为电子邮件创建新表.这个想法是将电子邮件地址存储为Array,但是如何在控制器和模型中实现呢? 这是控制器

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

是否可以在更新过程中检查email参数是否已经存在或是否为新参数,以及是否为新参数,将其添加到Array中? 我不知道自己是否清楚,但是无论如何,感谢您的回答或建议! 顺便说一句,我使用的是mysql,无法切换到其他版本!

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!

推荐答案

,您可以将其存储为逗号分隔的列表.

you can store it as a comma separated list.

或使用 rails序列化来完成这项工作

例如,

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

当以user.emails检索时将保持数组格式. 您始终可以验证数组中是否存在电子邮件.

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

这篇关于Rails数组和Mysql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆