开发者

Rails building a Serialized object of N records

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:

@myAtta开发者_开发知识库chmentsSerizliedIfANY = 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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜