Rails:动态命名实例变量(Rails: dynamically naming instance variables)

编程入门 行业动态 更新时间:2024-10-19 10:16:09
Rails:动态命名实例变量(Rails: dynamically naming instance variables)

只是想知道如何动态命名(例如,在循环中)一系列实例变量。 像这样的东西:

<% @current_issue.articles.each_with_index do |a, i| %> <% i += 1 %> <%= f.collection_select("article#{i}", @articles_hash1, :first, :last) %> <% @articles1.each do |r| %> <%= link_to(image_tag(r.image.url(:large)), r.image.url(:large), :id => 'article'+i.to_s+'_thumb'+r.id.to_s) %> <% end %> <% end %>

而不是@articles_hash1而是@articles_hash[i] 。 我只是不确定如何实现这一目标。

干杯!

Just wondering how to dynamically name (say, in a loop) a series of instance variables. Something like this:

<% @current_issue.articles.each_with_index do |a, i| %> <% i += 1 %> <%= f.collection_select("article#{i}", @articles_hash1, :first, :last) %> <% @articles1.each do |r| %> <%= link_to(image_tag(r.image.url(:large)), r.image.url(:large), :id => 'article'+i.to_s+'_thumb'+r.id.to_s) %> <% end %> <% end %>

Where instead of @articles_hash1 it'd be @articles_hash[i]. I'm just not sure how to achieve that.

Cheers!

最满意答案

<% @current_issue.articles.each_with_index do |a, i| %> <%= f.collection_select("article#{i}", @articles_hash[i], :first, :last) %> <% @articles_hash[i].each do |r| %> <%= link_to(image_tag(r.image.url(:large)), r.image.url(:large), :id => 'article'+i.to_s+'_thumb'+r.id.to_s) %> <% end %> <% end %>

我没有检查任何语法问题,但这应该做。

For anyone struggling with this, do yourself a favour and build an array of the instance variables in question, i.e.:

@articles = (1..3).to_a.map { |i| Article.all_articles(i).reverse }

And then loop through that array, i.e.:

<% @articles.each_with_index do |a, i| %> <% i += 1 %> <%= f.collection_select("article#{i}", @articles[i-1], :id, :name) %> <% end %>

更多推荐

本文发布于:2023-04-29 03:23:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1334520.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   实例   动态   Rails   variables

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!