29
31

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 5 years have passed since last update.

Railsで検索をSQLで簡単に実装する方法

Posted at

あらかじめ完成しているindexページに検索機能を追加する。今回はSQLでのLIKE演算子を使ったシンプルな検索を実現する。
Viewには

<%= form_tag stories_path, :method => "get" do %>
<%= text_field_tag :title, params[:title] %>
<%= submit_tag "検索"%>
<% end %>

と書いておいて、
controllerのindexメソッドには、機能追加前は

@products = Produc.all

と書いてあったりするけど、そのかわりに

@products = Product.where("title LIKE ?", "%#{params[:title]}%")

を書き足す。

これで完成。
いちおう%#{}%で囲ってエスケープはしてあるけど、もしかしたらSQLインジェクションの穴があるかも。セキュリティチェックが必要。

29
31
2

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
29
31

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?