I made a simple search form, that is basically searching through a couple of names on some items. I want to display the results on a new page, if the search query can be found in the name. I think it's really simple, just new to rails.
post_controler.rb -
class PostsController < ApplicationController
def index
@posts = Post.all
if params[:search]
@posts = Post.search(params[:search]).order("created_at DESC")
else
@posts = Post.all.order('created_at DESC')
end
end
end
routes.rb -
Rails.application.routes.draw do
get '/index' => 'posts#index'
resources :post, :posts
end
application.html.erb -
<!DOCTYPE html>
<html>
<head>
<title>Trial</title>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= stylesheet_link_tag "defaults", media: "all", "data-turbolinks-track" => true %>
<%= csrf_meta_tags %>
</head>
<body>
<%= yield %>
</body>
</html>
index.html.erb -
<html>
<body>
<div class="input-group">
<%= form_tag(posts_path, :method => "get", id: "search-form") do %>
<%= text_field_tag :search, params[:search], placeholder: "Search Posts", class: 'form-control' %>
<span class="input-group-btn">
<%= submit_tag "Search", class: 'btn btn-success' %>
</span>
<% end %>
</div>
</form>
</body>
</html>
post.rb
class Post < ActiveRecord::Base
def self.search(search)
where("name LIKE ?", "%#{search}%")
end
end
You can put this code in your index.html.erb file. It doesn't matter whether there is search parameter or not. Just put the following code below your form.
<% @posts.each do |post| %>
<p>
<%= post.name %>
</p>
<% end %>
Your controller code is fine. But doing the following will make it efficient. It will access database once.
def index
@posts = Post.all.order('created_at DESC')
@posts = @posts.search(params[:search]) if params[:search].present?
end
Updated for redirecting to new page
post_controller.rb
def search
@posts = Post.all.order('created_at DESC')
@posts = @posts.search(params[:search]) if params[:search].present?
end
routes.rb
resources :posts do
member do
post :search
end
end
search.html.erb
<% @posts.each do |post| %>
<p>
<%= post.name %>
</p>
<% end %>
Hope it helps you. And in the form_tag of index.html.erb change the path to search.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.