0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Rails 記事検索機能の実装

0
Last updated at Posted at 2022-02-18

結論

下記のコードを書けば大丈夫です

posts/search.html.erb
<h1>記事を検索する</h1>
<%= form_with url: search_posts_path, method: :get, local: true do |f| %>
<%= text_field_tag :content %>
<%= f.submit :検索 %>
<% end %>
<% @posts.each do |post| %>
<img src="<%= "/user_images/#{post.user.image_name}" %>">
<%= link_to(post.user.name, "/users/#{post.user.id}") %>
<%= link_to(post.content, "/posts/#{post.id}") %>
<% end %>
posts_controller.rb
def search
@posts = if params[:content].present?
Post.where('content LIKE ?', "%#{params[:content]}%")
else
Post.none
end
end

上のコードの解説(posts#seaechに検索機能を実装しています。)

1行目の解説

form_withを使います。(form_tag と form_for は Rails5.1で soft deprecated (非推奨) となっているそうです。)
入力された情報をデータベースに保存しないのでmodelに関しては記述しません。
url: search_posts_pathと指定することで、ユーザーが入力した文字列をposts_controllerのsearchアクションに送ります。
データを取得したいのでmethod: :getを指定します。
また、form_withはlocal: trueを入力していない場合、非同期通信(Ajaxによる通信)が行われます。
そのためlocal: trueを入力すれば、非同期通信をキャンセルし、HTMLとしてフォームの送信が可能になる。

2行目の解説

text_field_tagは、文字列入力用のスペースを実現することができるViewヘルパーです。

3行目の解説

サブミットボタンを生成します。

参考記事

【Rails 5】(新) form_with と (旧) form_tag, form_for の違い
サブミットボタンを生成
[Rails] form_with
Railsのform_withを使ってシンプルな検索機能を実装する

下のコードの解説

1行目の解説

送られてきた内容が存在するか

2行目の解説

where メソッドは、返されるレコードを制限するための条件を指定します
第一引数(content LIKE ?)の?の部分が、第二引数(%#{params[:content]}%)と置き換えられます。
%検索文字列%と表記することによって条件を満たすものを部分一致で返すようになってます.
例えば肉と入力すれば焼肉も肉食も出るということです。

参考記事

where メソッド
Railsの検索メソッドの基礎(whereでLIKE句を使う)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?