Rails 错误数组

发布于 2024-12-14 05:20:26 字数 527 浏览 2 评论 0原文

生成了一个数组属性

rails gen ... AddTaglistToPictures taglist:array

我使用在图片控制器的创建函数中

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

,在 if @picture.save 中,我有在上面,我有标签作为模型,使用nested_form gem构建(我需要一个模型以及列表)

当我制作了一组标签,我得到一个这样的列表

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

,这些是正确的标签,但它们实际上并不可用(因为尝试提取元素就像标签[0]是“-”,标签[4]是“n” '.)我该怎么做这个属性,以便正确格式化数组

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]
end
@picture.taglist = tagList
@picture.save

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

葮薆情 2024-12-21 05:20:26

如果要将数组存储在列中,则需要使用序列化关键字

class Photo
   serialize :tags, Array
end

,然后将标签列添加到字符串类型的照片类(如果有很多,则为文本)

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

class Photo
   serialize :tags, Array
end

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

七堇年 2024-12-21 05:20:26

"---\n- table\n- kevin\n- table\n- kevin\n" 是一个序列化的 yaml 数组。

尝试使用 YAML.load("---\n- table\n- kevin\n- table\n- kevin\n") 加载它。这应该会给你一个合适的红宝石数组。

"---\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.

給妳壹絲溫柔 2024-12-21 05:20:26

公平地说,您确实告诉它使用数组,因此它将序列化实际的数组。

IMO这应该是一个正常的关联:

class Photo
    has_many :tags
end

或者你可以使用 acts_as_taggable_on_steroids 或任何标签插件。

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
end

Or you could just use acts_as_taggable_on_steroids or any of the tagging plugins.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文