I'm building a website like www.reddit.com. I have Posts which can belong to eight categories. When a user clicks on a certain category, posts belonging to that category will show up. I was able to create the functionality to allow a user to do this and everything was working fine. I then made a search bar using the ransack gem and I got the search functionality working just fine. But now I can no longer click on categories to have the appropriate posts show up. I'm not sure how I messed this up and I have spent a considerable amount of time trying to figure it out. If anyone can point out the problem it would be greatly appreciated, thanks!
Posts Controller:
def index
@search_posts = Post.search(params[:q])
@search_results = @search_posts.result.paginate(:page => params[:page], :per_page => 10)
if params[:category_id]
@category = Category.find params[:category_id]
@posts = @category.posts.paginate(:page => params[:page], :per_page => 10)
else
@posts = Post.paginate(:page => params[:page], :per_page => 10)
end
end
I feel like it automatically executes the code in the else block but i'm not sure why because there is a params[:category_id] that comes in when I inspect my logs:
Started GET "/categories/7/posts" for ::1 at 2015-12-01 00:00:11 -0500
Processing by PostsController#index as HTML
Parameters: {"category_id"=>"7"}
Category Load (0.2ms) SELECT "categories".* FROM "categories" WHERE "categories"."id" = ? LIMIT 1 [["id", 7]]
(0.3ms) SELECT COUNT(*) FROM "posts"
Post Load (0.3ms) SELECT "posts".* FROM "posts" LIMIT 10 OFFSET 0
Posts#Index View:
<%= search_form_for @search_posts do |f| %>
<%= f.text_field :title_cont %>
<%= f.submit "Search" %>
<% end %>
<% if @search_results.any? %>
<% @search_results.each do |post| %>
<div id="each_post">
<p id="post_title"><%= link_to post.title, strip_url(post.url) %></p>
<p>Submitted <%= time_ago_in_words(post.created_at) %> ago by <%= link_to post.user.name, user_path(post.user) %></p>
</div>
<% end %>
<%= will_paginate @search_results %>
<% else %>
<% @posts.each do |post| %>
<div id="each_post">
<p id="post_title"><%= link_to post.title, strip_url(post.url) %></p>
<p>Submitted <%= time_ago_in_words(post.created_at) %> ago by <%= link_to post.user.name, user_path(post.user) %></p>
</div>
<% end %>
<%= will_paginate @posts %>
<% end %>
I'm sure this is not the correct way to pass the category id's but I got it working like this:
<%= link_to 'Gadgets', category_posts_path(1) %>
<%= link_to 'Sports', category_posts_path(2) %>
<%= link_to 'Gaming', category_posts_path(3) %>
<%= link_to 'Pics', category_posts_path(4) %>
<%= link_to 'World News', category_posts_path(5) %>
<%= link_to 'Videos', category_posts_path(6) %>
<%= link_to 'Aww', category_posts_path(7) %>
<%= link_to 'Music', category_posts_path(8) %>
Posts is nested under categories:
resources :categories do
resources :posts
end
Aucun commentaire:
Enregistrer un commentaire