0
1

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.

Ruby on Railsで検索機能を実装

Last updated at Posted at 2019-06-25
application.html
<%= form_tag("/posts/search", :method => 'get', :class => 'form') do %>
<div class="search-form">
<%= text_field_tag :search, '', class: 'search-input' %>
<%= submit_tag "検索", :name => nil, class: 'search-btn' %>
</div>
<% end %>
posts_controller.rb
def search
    @posts = Post.search(params[:search])
  end
post.rb
def self.search(search)
        if search
          Post.where('name LIKE? OR gender LIKE? OR country LIKE? OR job LIKE? OR content LIKE?',
                    "%#{search}%", "%#{search}%", "%#{search}%", "%#{search}%", "%#{search}%")
        else
          Post.all
        end
    end
search.html.erb
            <% @posts.each do |post| %>
            <div class="img-link">
                <a href="<%= "/posts/#{post.id}" %>" class="thumb-link">
                    <div>
                        <img src="<%= "/images/#{post.image}" %>" class="thumb-img">
                        <div class="thumb-name"><%= post.name %></div>
                    </div>    
                </a>
            </div>    
            <% end %>
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?