Ruby on Rails를 사용하여 간단한 블로그 응용 프로그램을 만들었습니다. 내 '투표'된 게시물을 /views/posts/index.html.erb보기에 표시하려고합니다. 다음은 기본 사항입니다.내 블로그에 가장 인기있는 게시물 표시 - Ruby on Rails
투표 테이블을 만들고 사용자가 /views/posts/show.html.erb 페이지의 게시물에 '투표'할 수있게했습니다. VotesController는 post_id를 Votes 테이블 열 post_id에 전달하고 해당 게시물의 투표 수를 ajax를 통해 동일한 표시 페이지로 반환합니다.
class Vote
belongs_to :post`
end
및
class Post
has_many :votes
end
내가 가진 게시물에 의해 주문 게시물 제목과는 투표 된 시간의 양, /views/posts/index.html.erb에 표시 할 것 최고 투표 수. 내가합니다 (/views/posts/show.html.erb 페이지에서)를 표시 할 수있게되었습니다 아래의 코드가 post_id를위한 투표 테이블과 vote_count에서 post_id를 가진
편집 . 즉 '55 (7) '이다. 궁금해지면 어떻게 든 post_title을 vote 테이블 (post_title 열)에 전달한 다음 post_id 대신 post_title을 표시 할 수 있습니다. 다음은이를 수행하는 코드입니다. 다음과 같은
class PostsController < ApplicationController
def index
@tag_counts = Tag.count(:group => :tag_name,
:order => 'count_all DESC', :limit => 20)
@vote_counts = Vote.count(:group => :post_id, :limit => 5)
conditions, joins = {}, nil
unless(params[:tag_name] || "").empty?
conditions = ["tags.tag_name = ? ", params[:tag_name]]
joins = :tags
end
@posts=Post.all(:joins => joins, :conditions=> conditions, :order => 'created_at DESC').paginate :page => params[:page], :per_page => 5
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @posts }
format.json { render :json => @posts }
format.atom
end
end
VotesController
class VotesController < ApplicationController
def create
@post = Post.find(params[:post_id])
@vote = @post.votes.create!(params[:vote])
respond_to do |format|
format.html { redirect_to @post}
format.js
end
end
end
/views/posts/index.html.erb
Most Liked Posts<hr/>
<% @vote_counts.each do |post_id, vote_count| %>
<div id="tag-wrapper">
<%= link_to(post_id, posts_path(:post_id => post_id)) %>
(<%=vote_count%>)</div>
<% end %>
당신이 [이 게시물]에서와 거의 같은 질문을 (요구하는지 알기나 해 http://stackoverflow.com/questions/2634981/how- 유사한 - 레코드 - 표시 - 개수 - 루비 - 온 - 레일)에 대한 검색을 수행 할 수 있습니까? 대답은 동일합니다. ** 요청 시간에 값을 계산하지 말고 counter_cache를 사용하십시오. –