gpt4 book ai didi

javascript - 在 Ruby on Rails 上构建 Javascript 对象数组的最佳方法

转载 作者:行者123 更新时间:2023-11-30 08:16:00 26 4
gpt4 key购买 nike

我有这个,但我很确定这不是构建它的最佳方式。

var dogs = {
'names' : ["a", "b", "c"],
'images': [
<% @dogs.images.each do |image| %>
{
'thumb' : '<%= image.thumb %>',
'medium' : '<%= image.medium %>',
} <%= "," unless(@dogs.images.last.id == image.id) %>
<% end %>
]
}

感谢您的帮助!

最佳答案

为什么不直接将图像转换为 json 对象,例如:

var dogs = {
'names' : ["a", "b", "c"],
'images': <%= @dogs.images.to_json %>
}

您还可以覆盖模型中的 to_json 方法以排除某些您不想显示的方法。

您可以在此处查看如何覆盖 to_json:

http://www.theirishpenguin.com/2008/05/19/quick-example-of-serialisation-via-to_json-in-ruby-on-rails/

关于javascript - 在 Ruby on Rails 上构建 Javascript 对象数组的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4020133/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com