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

发布于 2024-09-29 01:09:21 字数 346 浏览 3 评论 0原文

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

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 %>
  ]
}

感谢您的帮助!

I have this but I'm pretty sure that is not the best way to build it up.

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 %>
  ]
}

Thanks for your help!

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

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

发布评论

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

评论(1

忆离笙 2024-10-06 01:09:21

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

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

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

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

Why don't use just convert the images to a json object like:

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

You could also overwrite the to_json method in your model to exclude certain methods you don't want to display.

You can see how to overwrite to_json here:

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

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