无法加载特定类别的帖子

时间:2015-12-01 05:09:50

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4

我正在建立一个像www.reddit.com这样的网站。我的帖子可以属于八个类别。当用户点击某个类别时,将显示属于该类别的帖子。我能够创建允许用户执行此操作的功能,一切正常。然后我使用ransack gem创建了一个搜索栏,我的搜索功能运行得很好。但现在我再也无法点击类别来显示相应的帖子了。我不确定我是怎么搞砸的,我花了相当多的时间试图解决这个问题。如果有人能够指出这个问题,那将非常感谢,谢谢!

帖子控制器:

  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

我觉得它会自动执行else块中的代码,但我不确定为什么因为当我检查我的日志时有一个params [:category_id]:

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

帖子#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 %>

我确定这不是传递类别ID的正确方法,但我得到了这样的工作:

<%= 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) %>

帖子嵌套在类别下:

  resources :categories do
    resources :posts
  end

1 个答案:

答案 0 :(得分:0)

我能够通过设置&#39; @ search_results&#39;来解决这个问题。在控制器中为零:

if params[:category_id]
  @search_results = nil
  @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

并将if条件语句更改为:

<% if @search_results != nil %>

希望这可以帮助有类似问题的人。