0

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
4

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

6 Comments

you can display all the items from an array using flatten and map: @messages.map(&:link).flatten => [link, link, link, link]
court3nay, what I don't get is how you can mix the different objects. In this example the first link belongs to message(1) and the other three to message(2)?
Yes. Since it's not obvious what you want to do with the links, I'm giving you some general ruby ideas :) You might want to make a separate class/table for links with has_many association
Basically, when a user creates a chat message the link gets saved, so the users can find all the links from a conversation. I'm not sure if I need a new class. I will just display the links as a list (kinda index page), and if user click on one of them then gets to the given page. So besides recognizing links in chat messages and displaying them I do nothing with the links. What do you think? Do I need a separate class?
court3nay, plz take a look at the updated question. I would like to display 12 links with created_at attribute, but since @message_links2 is an array I can't call the pagination on it and it doesn't contain the created_at date. If I call the pagination on the message.with_links objects like in the current code then the number of links will vary since it's unknown how many links an object has.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.