Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

rails search機能を導入しているのですがNoMethodErrorが発生してしまいます 初心者のため見落としかもしれません

解決したいこと

search機能をrailsに実装しているのですが、ページネーションといいねの数が邪魔をして検索が機能しなくなってしまいました。

発生している問題・エラー

like_count.error
NoMethodError in Posts#search
Showing /Users/app/views/posts/index.html.erb where line #41 raised:

undefined method `[]' for nil:NilClass

@output_buffer.safe_append='          '.freeze;@output_buffer.append=( @post_like_count[post.id] );@output_buffer.safe_append='          
                                                                                       ^^^^^^^^^

<%= @post_like_count[post.id] %>   
paginate.error
NoMethodError in Posts#search
Showing /Users/app/views/posts/index.html.erb where line #47 raised:

undefined method `total_pages' for #<ActiveRecord::Relation [#<Post id: 2, content: "asdfaadaa", title: "dsfa", created_at: "2023-02-24 21:57:19.528378000 +0900", updated_at: "2023-02-24 21:57:19.528378000 +0900", user_id: 1>, #<Post id: 4, content: "asdfafsd", title: "dfadf", created_at: "2023-02-27 15:59:41.620757000 +0900", updated_at: "2023-02-27 15:59:41.620757000 +0900", user_id: 1>, #<Post id: 6, content: "fasdf", title: "fasdfa", created_at: "2023-03-02 14:42:46.430446000 +0900", updated_at: "2023-03-02 14:42:46.430446000 +0900", user_id: 1>, #<Post id: 7, content: "asdfa", title: "fasdf", created_at: "2023-03-02 14:42:50.782476000 +0900", updated_at: "2023-03-02 14:42:50.782476000 +0900", user_id: 1>, #<Post id: 8, content: "fasdfsas", title: "dsafsd", created_at: "2023-03-02 14:42:53.704776000 +0900", updated_at: "2023-03-02 14:42:53.704776000 +0900", user_id: 1>, #<Post id: 9, content: "asdf", title: "fasdfa", created_at: "2023-03-02 14:42:56.302068000 +0900", updated_at: "2023-03-02 14:42:56.302068000 +0900", user_id: 1>, #<Post id: 11, content: "fasdfa", title: "sadfa", created_at: "2023-03-02 14:43:03.934720000 +0900", updated_at: "2023-03-02 14:43:03.934720000 +0900", user_id: 1>, #<Post id: 12, content: "adsfsaf", title: "fasdf", created_at: "2023-03-02 14:43:09.533745000 +0900", updated_at: "2023-03-02 14:43:09.533745000 +0900", user_id: 1>, #<Post id: 13, content: "adasfasdfasdf", title: "fasdf", created_at: "2023-03-02 14:43:15.077459000 +0900", updated_at: "2023-03-02 14:43:15.077459000 +0900", user_id: 1>, #<Post id: 14, content: "adasfasdfasdf", title: "fasdf", created_at: "2023-03-02 14:43:15.287900000 +0900", updated_at: "2023-03-02 14:43:15.287900000 +0900", user_id: 1>, ...]>

<%= paginate @posts %>

該当するソースコード

posts/index.html.erb
  <div class="search">
    <%= form_with url: searches_path, method: :get, local: true do |f| %>
      <%= f.text_field :keyword, placeholder: "\uf002 企画を検索", value: @keyword, class: "fa search-input"%>
      <%= f.submit "\uf002", class: "fa search-submit" %>
    <% end %>
 </div>
〜省略〜
    <% @posts.each do |post| %>
      <div class="posts-index-item">
        <div class="post-left">

        <% if post.user.avatar? %>
          <%= link_to (image_tag post.user.avatar_url), "/users/#{post.user.id}" %>
        <% else %>      
          <%= link_to (image_tag src="default.jpg"), "/users/#{post.user.id}" %>
        <% end %> 
          
        </div>
        <div class="post-right">
          <div class="post-user-name">
            <%= link_to(post.user.name, "/users/#{post.user.id}") %>
          </div>
          <div class="post-title">
            <%= link_to(post.title.truncate(30), "/posts/#{post.id}") %>
          </div>

          <% if @current_user && Like.find_by(user_id: @current_user.id, post_id: post.id) %>
            <%= link_to("/likes/#{post.id}/destroy", {method: "post"}) do %>
              <span class="fa fa-heart liked-btn"></span>
            <% end %>
          <% else %>
            <%= link_to("/likes/#{post.id}/create", {method: "post"}) do %>
              <span class="fa fa-heart unliked-btn"></span>
            <% end %>
          <% end %>
          <%= @post_like_count[post.id] %> <-------error         
          
        </div>
      </div>
    <% end %>

    <div class="paginate">
      <%= paginate @posts %> <-------error
    </div>

posts_controller.rb
  def index
    @posts = Post.all.order(created_at: :desc).page(params[:page])
    @post_like_count = Like.group(:post_id).count
  end
  
  def show
    @post = Post.find_by(id: params[:id])
    @user = @post.user
    @likes = Like.where(user_id: @user.id)
    @likes_count = Like.where(post_id: @post.id).count
    @comments_count = Comment.where(post_id: @post.id).count
    @comment = Comment.new
    @comments = @post.comments.includes(:user)
    @post_detail = Post.find(params[:id])
    if @current_user.present?
      unless ViewCount.find_by(user_id: @current_user.id, post_id: @post_detail.id)
        @current_user.view_counts.create(post_id: @post_detail.id)
      end
    end
  end
〜省略〜
  def search
    @posts = Post.search(params[:keyword])
    @keyword = params[:keyword]
    render "index"
  end

最後まで読んでいただきありがとうございます
ご教授いただけると幸いです

0 likes

2Answer

def index
  @posts = Post.all.order(created_at: :desc).page(params[:page])
  @post_like_count = Like.where(post_id: @posts.pluck(:id)).group(:post_id).count
end

def search
  @posts = Post.search(params[:keyword])
  @posts = @posts.page(params[:page])
  @post_like_count = Like.where(post_id: @posts.pluck(:id)).group(:post_id).count
  @keyword = params[:keyword]
  render "index"
end

kaminariでpagerを使うためには.page(params[:page])を使う必要があります。

0Like

Comments

  1. @NetaNeta0620

    Questioner

    ```
    def show
    @post_detail = Post.find(params[:id])
    if @current_user.present?
    unless ViewCount.find_by(user_id: @current_user.id, post_id: @post_detail.id)
    @current_user.view_counts.create(post_id: @post_detail.id)
    end
    end
    end
    ```


    ```
    def index
    @posts = Post.all.order(created_at: :desc).page(params[:page])
    @post_like_count = Like.where(post_id: @posts.pluck(:id)).group(:post_id).count
    @post_comments_count = Comment.where(post_id: @posts.pluck(:id)).group(:post_id).count
    end
    ```
    に追加したいのですがどう組めばいいのか教えていただけないでしょうか?

    何度もすみません

毎回助けていただいてありがとうございます。
問題なく動くようになりました。
ありがとうございました!

0Like

Your answer might help someone💌