Sean Magyar
Sean Magyar

Reputation: 2380

Extract elements from a string representing an array

My message object has a link attribute @message.link, which is a string. Before saving message.link to db I URI.extract from message.body:

["http://getbootstrap.com/javascript/#tabs", "http://paulgraham.com/re.html"]

Once I save it to the db message.link will be saved as:

"[\"http://getbootstrap.com/javascript/#tabs\", \"http://paulgraham.com/re.html\"]"

When I fetch the data from db later on how can I get the array from the message.link string like this?

["http://getbootstrap.com/javascript/#tabs", "http://paulgraham.com/re.html"]

To display the links from all message objects, how should I extract the links? Let's say message(1).link has one link, message(2) has three links, and I'd like to display all the four links as separated elements of @message_links or whatever instance variable.

UPDATE

Method works but can't display the :created_at and do the pagination properly since @message_links2 will be an array of links.

@message_links = @conversation.messages.with_link.order(created_at: :desc).paginate(page: params[:page], per_page: 12)
@message_links2 = @message_links.map(&:link).flatten

Upvotes: 0

Views: 169

Answers (1)

court3nay
court3nay

Reputation: 2365

This is where you want a serialized column. Then you won't need to do the conversion yourself. see: Using Rails serialize to save hash to database

Upvotes: 1

Related Questions