在索引视图中重复发布post

我试图通过使用acts_as_votable gem的upvotes数来对我的问题进行排序。 一切都很好,除了它显示整套问题n次,其中n是问题的#。 例如。 我发布了3个问题A,B和C,它将显示ABC ABC ABC。

这是我的观看代码:

 

这是我的控制器代码:

 def upvote @question = Question.find params[:id] @question.liked_by current_user redirect_to comment_questions_path end def index @comment = Comment.find params[:comment_id] @questions = @comment.questions end 

Github上

感谢帮助!

问题出在你的_question.html.erb部分。

当您在index.html.erb执行<%= render @questions %>时,该呈现调用将负责循环@questions集合,并为每个question呈现部分_question.html.erb 。 问题在于,在您的部分中,您使用<% @comment.questions.order("cached_votes_total desc").each do |question| %>再次迭代所有<% @comment.questions.order("cached_votes_total desc").each do |question| %> <% @comment.questions.order("cached_votes_total desc").each do |question| %>

要解决这个问题,您只需要删除_question.html.erb第一行中的循环,因为<%= render @questions %>与以下内容相同:

 <% @questions.each do |question| %> <%= render 'question', question: question %> <% end %> 

关于渲染集合的Rails文档: http : //guides.rubyonrails.org/layouts_and_rendering.html#rendering-collections

index.html.erb您正在进行render @questions 。 这将呈现集合@questions以便为该集合中的每个项目呈现。

它在_question.html.erb呈现视图。 在该文件中,您有<% @comment.questions.order("cached_votes_up desc").each do |question| %> <% @comment.questions.order("cached_votes_up desc").each do |question| %> 。 这就是为@comment呈现每个问题。

您真的想要在评论视图中呈现评论,并显示该评论的问题,或者呈现与评论无关的问题集。 两者一起做会给你多样性。

通过阅读你的问题,我不太了解,但这可能会有所帮助

 <% @comment.questions.select("DISTINCT(questions.id), *").order("cached_votes_up desc").each do |question| %>