Rails mala matriz

I generated an array attribute using

rails gen ... AddTaglistToPictures taglist:array

In my create function in my Pictures controller, in if @picture.save , i have

tagList =[]
tags = @picture.tags
tags.each do |tag|
  tagList += [tag.tagcontent]
@picture.taglist = tagList

In the above, i have Tag as model, built with nested_form gem (I need a model as well as the list)

When i make a group of tags, i get a list like this

"---\n- table\n- kevin\n- table\n- kevin\n"

these are the right tags but they aren't really useable (because trying to pull out elements is like tag[0] is '-', tag[4] is 'n'.) How do i make this attribute so it formats the array properly

preguntado el 08 de noviembre de 11 a las 15:11

3 Respuestas

If you want to store an array in a column you need to use the serialize keyword

class Photo
   serialize :tags, Array

then add a tags column to Photo class of type string (or text if there will be many)

respondido 08 nov., 11:19

"---\n- table\n- kevin\n- table\n- kevin\n" is a serialized yaml array.

Try loading it with YAML.load("---\n- table\n- kevin\n- table\n- kevin\n"). That should give you a proper ruby array.

respondido 08 nov., 11:19

your answer sort of works, it wont take just pic.taglist = YAML.load(pic.taglist). how do i change the actual array so i can pass it as a regular array through a AJAX call into javascript - Kevin

Does that comment make sense (I mean i cant just do YAML.load(pic.taglist) in javascript ) - Kevin

You can convert the array to json if you want to pass it to javascript. - Escarcha

How can i do that, i tried something simple like pic.taglist.to_json which gives me "\"---\\n- table\\n- kevin\\n- table\\n- kevin\\n\"" , I also ... nevermind, how do i do that. sorry if that sounds kind of dumb, but i don't know how to output the taglist as json (within my Picture json array which was made automatically) - Kevin

Oh, yeah, you'd have to convert it from a serialized YAML object first, which would make the code a bit messier (YAML.load(pic.taglist).to_json). - Escarcha

In fairness, you did tell it to use an array, so it's going to serialize an actual array.

IMO this should be a normal association:

class Photo
    has_many :tags

O simplemente podrías usar acts_as_taggable_on_steroids or any of the tagging plugins.

respondido 08 nov., 11:19

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.