Rails building a Serialized object of N records

僤鯓⒐⒋嵵緔 提交于 2020-01-14 02:46:12

问题


I want to serialize any object(s) in text columns.

Via an API, I get the params:

params[:attachments] -- this can be 0 or 1 or 3, or 100+ etc...
params[:attachment1]...params[:attachment2] ... params[:attachmentN]

So how do I store X # of attachments in a serialized object?

mailThing = MailThing.create(:attachments => myAttachmentsSerizliedIfANY )

I'm trying to do:

@myAttachmentsSerizliedIfANY = nil

i = 0
attachmentCount = params[:attachments].to_i
while i < attachmentCount do

   @myAttachmentsSerizliedIfANY << params[:attachment + i ]

   i += 1
end

Any suggestions on how to get this working? thanks


回答1:


Okay, so I looked at some of your other questions, and I think I might have something that will work for you. For this to work, you will need to have a column in the database (I'll call it attachment_storage) where you can store these attachments after you serialize them.

Basically you want to get the attachments into an array first, and then serialize it into a string so that you can store it into the database.

Here's some code to get that done.

attachment_storage = []
(1..params[:attachments].to_i).each do |attachment_num|
   attachment_storage << params["attachment#{attachment_num}".to_sym]
end

Here we're building the symbols for the params hash using the string and to_sym to turn it into a symbol like :attachment1, :attachment2, etc.

Then you want to put in the database, so you can store it as noted in the [ActiveRecord Documentation][1] under the section "Saving arrays, hashes, and other non-mappable objects in text columns".

In order for the serialization to work, you need to add serialize :attachment_storage to your model, and then to store it you would assign it just like any other parameter as above. Then save your model and it will be serialized for you.



来源:https://stackoverflow.com/questions/4869382/rails-building-a-serialized-object-of-n-records

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!