ssoushi0307
@ssoushi0307

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

ruby on rails で検索機能を付けたいです。

Ruby on RailsでQiitaのようなteitterのようなアプリをつくっています。
prog-8のWeb開発コース(Ruby on Rails)を完成させ次に投稿の検索機能を実装しようとしたときにエラーが発生しました。
解決方法を教えて下さい。

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

undefined method `user' for nil:NilClass

該当するソースコード

posts_controller.rb
  def show
    @post = Post.find_by(id: params[:id])
    @user = @post.user
    @likes_count = Like.where(post_id: @post.id).count
  end

追加したコード

posts_controller.rb
def search
    @teams = Post.search(params[:search])
  end
post.rb
def self.search(search)
        if search
          Post.where(['address LIKE ?', "%#{search}%"])
        else
          Post.all
        end
      end
routes.rb
get "posts/search" => "posts#search"
index.html.erb
<div class="serch_form">
<%= form_tag(posts_search_path,:method => 'get') do %>
  <%= text_field_tag :search %>
  <%= submit_tag 'Search', :address => nil %>
<% end %>
</div>

自分で試したこと

https://qiita.com/a_hyu/items/530d0a8e62a60f180ee4
これを参考にしました。
また初めて投稿するので気を付けた方がいいところがあれば教えてください。

2

2Answer

    @post = Post.find_by(id: params[:id])

userメソッドのレシーバがnilになってしまっていることが原因のエラーなので、上記の箇所でうまくデータが取れてないのかなと思います!

コードブロックのインデントを揃えるともっといいかもです!

post.rb
  def self.search(search)
    if search
      Post.where(['address LIKE ?', "%#{search}%"])
    else
      Post.all
    end
  end
0Like

エラーが予測される箇所については
先の回答に記載されているので
別の回答になりますがRansackという
検索機能を簡易実装できるgemがあるので
もしよろしければご検討ください。

0Like

Your answer might help someone💌