Ruby on Rails - 使用 each_slice 时查找最后一轮
Ruby on Rails - Find Last round when using each_slice
我在我的应用程序中使用 each_slice
每 4 张图片显示一个 广告代码。
我是这样做的:
- @post.images.each_slice(4) do |group|
- group.each do |image|
// My images
%div.ads
// My ads code
我怎样才能找到最后一轮并阻止它显示 广告 因为我不想在最后一轮显示广告。
我已经按照这里说的做了,但是运气不好:How to know that we're on "the last round" of a .each_slice
我在我的 post_controller
中添加了 last_slide
方法,当我在我的 [=17] 中 run/before_action 时得到了错误的参数数量=]-view 当我不在我的控制器中 运行 时,没有任何反应。
为了实现在每 4 张图片之间插入一个广告的目标,您可以利用 Rails' 带有集合和 spacer_template 选项的渲染方法。
# The view
= render partial: 'image_group', collection: @images.each_slice(4).to_a, spacer_template: 'advertisement'
# _image_group.html.haml
= render partial: 'image', collection: image_group
# _image.html.haml
// Your image code
# _advertisement.html.haml
%div.ads
// Your Ads Code
可以通过两种不同的方式完成。第一个是 简单,而第二个解决方案更复杂。
1 解决方案(感谢 jphager2):
if group.include?(images.last)
2 解决方案:
- @post.images.each_slice(2).each_with_index do |group, index|
- group.each_with_index do |image|
// your code
- if index < group.size
// Ad code
我在我的应用程序中使用 each_slice
每 4 张图片显示一个 广告代码。
我是这样做的:
- @post.images.each_slice(4) do |group|
- group.each do |image|
// My images
%div.ads
// My ads code
我怎样才能找到最后一轮并阻止它显示 广告 因为我不想在最后一轮显示广告。
我已经按照这里说的做了,但是运气不好:How to know that we're on "the last round" of a .each_slice
我在我的 post_controller
中添加了 last_slide
方法,当我在我的 [=17] 中 run/before_action 时得到了错误的参数数量=]-view 当我不在我的控制器中 运行 时,没有任何反应。
为了实现在每 4 张图片之间插入一个广告的目标,您可以利用 Rails' 带有集合和 spacer_template 选项的渲染方法。
# The view
= render partial: 'image_group', collection: @images.each_slice(4).to_a, spacer_template: 'advertisement'
# _image_group.html.haml
= render partial: 'image', collection: image_group
# _image.html.haml
// Your image code
# _advertisement.html.haml
%div.ads
// Your Ads Code
可以通过两种不同的方式完成。第一个是 简单,而第二个解决方案更复杂。
1 解决方案(感谢 jphager2):
if group.include?(images.last)
2 解决方案:
- @post.images.each_slice(2).each_with_index do |group, index|
- group.each_with_index do |image|
// your code
- if index < group.size
// Ad code