简体   繁体   中英

How to iterate through array of strings from database Ruby on Rails

I save an array of strings to my rails database, but when I go to use it in the view, I believe it is printing the string definition of the array. Am I dealing with JSON here? (aka when it saves to the database is it just an array wrapped in a string?)

How do I have it so that in my view, it simply displays the items?

<%= record.items %>

displays inside my html tag:

["item1", "item2", "item3"]

I tried iterating through record.items.each do |item| but that did not work.

If you're saving an "exact" array as a String, then Array#each won't work, because isn't a method in the String class.

Maybe isn't the best option, but you could use JSON.parse and this way get your array and be able to iterate over each object inside:

require 'json'

str = '["item1", "item2", "item3"]'
JSON.parse(str).each { |item| p item }
# "item1"
# "item2"
# "item3"

In order this work your string must be an array, in your example the second item is missing its double quote.

You could consider working with serialization or array data types depending on you current database.

A better approach to your issue is to serialize your items column. I think by default it's Array but you can use Hash or JSON.

class Record < ActiveRecord::Base
  serialize :items
end

Calling record.items returns the data exactly the way you need. If you go with this you'll have to update your old records to support it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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