2016-10-24 18 views
1

在posts控制器對象包含所有活動的帖子:檢查下一個活動的記錄存在

@posts = Post.where(status: 'active').order(:name) 

在查看此對象被重複,我必須執行基於下一篇文章存在的一些操作。

<% @posts.each do |post| 
    if post.next_post_exists? 
    # do something. 
    else 
    # delete author. 
    end  
    end 
%> 

那麼,什麼是檢查接下來的文章中存在的最好方法?

def next_post_exists? 
    #TODO 
end 

回答

1

您可以簡單地爲當前帖子取一個變量,然後檢查是否存在下一篇文章。 例如:

<%i=0 
@posts.each do |post| 
    if @posts[i+1].present? 
    #do something 
    else 
    #delete author 
    end 
    i+=1 
end%> 

試試這個,讓我知道,如果它的工作原理。

0
class Post 

    def next 
    self.class.find_by("id > ?", id) 
    end 

end 

而在這一點上,你可以這樣做:

<% @posts.each do |post| 
    if post.next.present? 
    # do something. 
    else 
    # delete author. 
    end  
    end 
%>