I am trying to allow a user to click on a month and have the posts for that month be listed (sort of like doing a search, but without the search form). I want them to be able to just click the month name.
I can create an archive of the posts connected to certain months and have them displayed in the sidebar, but I want the posts for that month to replace the posts listed in the index action for the posts.
Here is the code I am using for the archive currently...
In the Posts Controller...
def index
@posts = Post.find(:all, :order => "created_at DESC")
@recent_posts = Post.all(:order => "created_at DESC")
@posts_by_month = Post.find(:all, :order => "created_at DESC").group_by { |post| post.created_at.strftime("%B %Y")}
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @posts }
end
end
Here is what is in the corresponding index view...
blog.archive<% @posts_by_month.each do |monthname, posts| %>
<p class="month-archive"><%= monthname %></p>
<div class="archive">
<ul class="archive">
<% posts.each do |post| %>
<li class="archive"><p class="archive-post"><%= post.title %></p></li>
<% end %>
</ul>
</div>
This will list the posts based on the month they were created in, but this only gets me halfway there. I want the user to be able to click on the month and have it show the entire posts, and not just a listing in the sidebar.
Hope that makes some sense.
开发者_如何学GoAny help is appreciated. I've tried finding an example somewhere to look at so that I can wrap my head around how to do it and have not been able to.
Thanks!
Aaron...newby to Ruby
I think you would need to create a new method something called 'month' in Posts controller, and also create a routing something like
match 'posts/month/:month' => 'Posts#month', :as=> posts_by_month
in a new method in Posts controller, you would use argument params[:month]
to select the adequate articles with :month=>params[:month]
edit
In a view page, you would create each month to link to posts/month/:month
where :month
would be any month related string that you have chosen.
Also, it seems that you are fetching same data twice.. It seems that @posts and @recent_posts are doing the same job. You may want to eliminate one of them to improve the performance.
精彩评论