2016-07-14 116 views
0

我在我的应用程序中使用each_slice来显示广告代码每4张图片。Ruby on Rails - 在使用each_slice时查找上一轮

我这是怎么做的吧:

- @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并得到错误的参数数目,当我运行/ before_action在我show - 视图,当添加last_slide方法我没有在我的控制器中运行,没有任何反应。

+0

if语句,你可以将其括在一个像这样'如果image.id = images.last! .id' –

+0

是或'如果group.include?(images.last)' – jphager2

+0

@AAnkudovich它没有工作:/ – Rubioli

回答

0

它可以以两种不同的方式完成。第一个是简单一个,而第二个解决方案更复杂。

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 
0

为了实现您在每4张图片之间插入广告的目标,您可以利用Rails的渲染方法以及collection和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