简体   繁体   English

如何在MySQL的Ruby哈希中存储多个电子邮件?

[英]How to store multiple emails in Ruby hash in MySQL?

I built my own comments in my rails app without threading and I want to be able to send reply all notifications for new comments on a project. 我在Rails应用程序中构建了自己的注释,而没有线程,我希望能够发送答复项目中所有新注释的所有通知。 Would it be best to just store emails into a ruby hash in MySQL and then read from it when necessary? 最好只将电子邮件存储到MySQL中的ruby哈希中,然后在需要时从中读取吗? I'm trying to figure out how to insert emails into a hash with keys I don't have to define, any help? 我试图弄清楚如何使用不需要定义的键将电子邮件插入哈希,有什么帮助吗?

Assuming you have some column with string type in some mysql table. 假设您在某些mysql表中有一些string类型的列。

Use json gem. 使用json gem。 If you don't have json gem install it by gem install json . 如果您没有json gem,请通过gem install json进行gem install json

require 'json'
reply_emails_list = ["a@gmail.com", "b@gamil.com"]
obj.column_name = {:emails => reply_emails_list}.to_json  #storing ruby hash as string in mysql

To get ruby hash back use `JSON.parse(obj)' 要获取红宝石哈希,请使用JSON.parse(obj)

emails_list = JSON.parse(obj.column_name)  #ruby hash

or 要么

In rails way. 在铁轨的方式。 In model you can do like this: 在模型中,您可以这样:

YourModel < ActiveRecord::Base
  serialize :column_name, Array  #If don't want hash
  serialize :column_name     #you can store key value pair as I shown above
end

Using second will avoid converting from hash to json and vice versa 使用second将避免从hash转换为json ,反之亦然

In Postgres, there is an array extension you can use to get actual array storage. 在Postgres中,有一个数组扩展名可用于获取实际的数组存储。 Unfortunately, this doesn't work for MySQL. 不幸的是,这不适用于MySQL。

The best thing for data like e-mails would be to serialize your list of emails as a String field and provide a synthetic attribute that provides an array accessor (if needed). 对于像电子邮件这样的数据,最好的方法是将电子邮件列表序列化为String字段,并提供一个提供数组访问器的综合属性(如果需要)。 You can then put callbacks on your comment to update the email list when Comments are added to this Project. 然后,您可以在评论上添加回调,以在将评论添加到该项目时更新电子邮件列表。

class Project < ActiveRecord::Base
  # db String field email_list
  attr_accessor :emails

  def emails
    email_list.split(',')
  end

  def emails=(email_ary)
    self.email_list = email_ary.join(',')
  end
end

This can be a good alternative to using a JSON blob, as it allows easier text searching and handling of a comma separated list. 这可以替代使用JSON blob,因为它使文本搜索和逗号分隔列表的处理变得更加容易。 I don't know if split() or JSON.parse provide an advantage in terms of serialization performance. 我不知道split()或JSON.parse是否在序列化性能方面提供了优势。

According to ActiveRecord::Base you can serialize a column: 根据ActiveRecord::Base您可以serialize列:

class MyModel < ActiveRecord::Base
  serialize :emails
end

User.create(:emails => %w( email1@a.com email2@b.com email3@c.com )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM