Ruby on rails how can I search my table by keyword? - ruby-on-rails

I have this table relationship like:
certificate belongs_to programs
certificate belongs_to users
And I have a form in the certificate view page to get the keyword params.
I want to search for user name and email by the form.
How can I get this done in controller?
<%= form_tag admin_program_path(#program), :method => :get do %>
<%= text_field_tag :keyword, params[:keyword], :placeholder => "Search by name or email", :class => "form-control rounded" %>
<%= submit_tag "Search", :class => "btn btn-outline-secondary" %>
<% end %>
I was trying as below, but it can't work.
Please help me.
#certificates = #program.certificates.includes(:user).order("id DESC")
if params[:keyword].present?
keyword = "%#{params[:keyword].strip}%"
#certificates = #certificates.user.where('name LIKE ? OR email LIKE ?', keyword, keyword)
end

1: find all users by keyword
2: find by found certificates users' ids
users = User.where('name LIKE ? OR email LIKE ?', keyword, keyword)
#certificates = #certificates.where(user_id: users.pluck(:id))
OR joins the users table and use something like #certificates.where('name LIKE ?', keyword)

You are not querying on the users table properly. You need to join the users table with the certificates table and modify your where statement and use users. on name and email as these attributes belong to the users table.
This should work:
#certificates = #program.certificates.joins(:user).includes(:user).order("id DESC")
if params[:keyword].present?
keyword = "%#{params[:keyword].strip}%"
#certificates = #certificates.where('users.name LIKE ? OR users.email LIKE ?', keyword, keyword)
end

Related

Search for a nested resource

I have an event with many guests for that event. A guest must search themselves using their ID to RSVP but I cannot get the search to return that guests info (show/edit page).
The search tag:
<div>
<h3>Enter your ID here:</h3>
<%= form_for "", url: event_guest_path(#event,#guest), role: 'search', method: :get do %>
<%= text_field_tag :search, #search_term, placeholder: "Search.." %>
<% end %>
</div>
GuestController:
def show
if params[:search]
#search_term = params[:search]
#guest = #event.guests.search_by(#search_term)
end
end
Guest.rb:
def self.search_by(search_term)
where("(id) LIKE :search_term", search_term: "%#{search_term}%")
end
At the moment it keeps taking me to the index page but I want it to return the guest path where they can make their RSVP.
We should have a more precision to clearly answer you. Because your query like a bit overkill.
A guest have a unique ID for a specific event ?
If that is the case I suggest you to simply use the following code in your show:
Guest.find_by(search_term: params[:search])
If your Guest has a unique ID which can be used for multiple event you probably want to create a join table but I am speculating.

Rails Search and add filters to the search - geocoder

I would like some advices on the way to add a filter , on my search form with geocoder.
I got a User model and Animal model (animals got a Type argument)
And a join table : Animal_User with Animal_ID / User_ID)
Right now, I can locate Users around a city with the choice of Kilometers around that city.That's working fine.
I would like to add the filter on the type of animal, that would be great :)
Search would look like this : London > 10KM > Filter on Type : dogs
Many thanks in advance if you have a glimpse of an idea on how to do that. You will find the search html and the controller. If you need User Model or Animal model i can post it too ( it's really standard Has_many / has_many though association)
search.html.erb
<div class="search-bar">
<%= form_tag search_path, :class => "webdesigntuts-workshop", method: :get do %>
<%= label :user, "" %>
<%= text_field_tag :city, params[:city], placeholder: 'City', :input_html => { :value => 'Paris' } %>
<%= label :distance, "" %>
<%= text_field_tag :distance, params[:distance], placeholder: 'km', :input_html => { :value => '10' } %>
<%= submit_tag "Search" %>
<% end %>
</div>
search controller
class SearchsController < ApplicationController
def search
if params[:city].present?
#searchs = User.near(params[:city], params[:distance] || 10).where("id != ?", current_user.id)
else
#searchs = User.all.where("id != ?", current_user.id)
end
end
end
Try this, I'm basing it on Active Record Querying:
User.joins(:animals).where(id: current_user.id, animals: {type: params[:animal_type]}).near(params[:city], params[:distance] || 10)
This assumes that your User model has_many :animals (being able to write Rails models DSL like this is awesome)

Generate search results for users by city in Rails 4

At the moment I am trying to create a search within a project to bring up users depending on their region. From what I understand, I basically need to place the search params in the controller, the self.search method in the model, and then the form in the view.
In another project, I have a search but it shows all the options above and use the search to filter out those which do not match. For this situation, I do not want to list any users in the beginning. I want to use the search bar and bring up any users that match within that view page. Additionally I use Devise for users if that does make a difference. Here are my three regions of code:
Model (user.rb):
def self.search(search)
where("state ILIKE ?", "%#{search}%")
end
Controller (welcome_controller.rb):
def index
#users = User.all.order("created_at DESC")
#newusers = User.all.order("created_at DESC").limit(5)
#differentlocations = User.all.group_by(&:state).count
render :layout => 'with_newest_members'
if params[:search]
#users = User.search(params[:search]).order("created_at DESC")
else
#users = User.all.order('created_at DESC')
end
end
View (find.html.erb):
<%= form_tag(find_path, :method => "get") do %>
<%= text_field_tag :search, params[:search], placeholder: "Search Posts" %>
<%= submit_tag "Search", :name => nil %>
<% end %>
Please let me know if you have any knowledge for me to help =) Any additional explanation would be greatly appreciated to help me understand, thank you!
Edit: I know I need to enter the results portion but I am confused about how/where to put it.
Joe
ANSWER:
The issue was in my controller because I had a render command prior to the search code. The controller should be:
def index
#users = User.all.order("created_at DESC")
#newusers = User.all.order("created_at DESC").limit(5)
#differentlocations = User.all.group_by(&:state).count
if params[:search]
#users = User.search(params[:search]).order("created_at DESC")
else
#users = User.all.order('created_at DESC')
end
render :layout => 'with_newest_members'
end
Fantastic =)
Two small things that might help:
1) In your Search model, I believe you have a typo in your search method. It should read as follows:
def self.search(search)
where("state LIKE ?", "%#{search}%")
end
You might also want to consider a more description name for your argument, such as state.
2) In your form, you don't need to explicitly write params[:search] anywhere. The params hash will be generated for you in the controller, with the name of the text_field as the key and the value inputted by the user as the value (see Ruby docs here). In this case, use :search as the name of the text_field_tag name.
<%= form_tag(find_path, :method => "get") do %>
<%= text_field_tag :search, placeholder: "Search Posts" %>
<%= submit_tag "Search", :name => nil %>
<% end %>
More on FormHelpers here.

Ruby on Rails - Search on Model Index

I want to be able to search and update the index.
this is my controller method:
def index
if params[:search]
#ofertas = Oferta.search(params[:search]).paginate(page: params[:ofertas_page], :per_page => 5)
else
#ofertas = Oferta.all.paginate(page: params[:ofertas_page], :per_page => 5)
end
end
My search method in the model
def self.search(search)
where("titulo like ?","%w{search}%")
end
and this is the search form
<%= form_tag ofertas_path, :method => 'get' do %>
<p>
<%= text_field_tag :search, params[:search], placeholder: "Procurar Entidades" %>
<%= submit_tag "Procurar", :name => nil %>
</p>
<% end %>
I've seen this setup in a number of search tutorials but no matter what I type nothing appears. Does someone know what I'm doing wrong?
It looks like you were trying to interpolate the search variable into the string, but didn't quite get the right symbol. How about this:
"%#{search}%"
Note the # instead of the w.
where("titulo like ?","%w{search}%")
should be:
where("titulo like ?", "%#{search}%")
#{xxx} is for string interpolation - it allows you to inject ruby (including variables) into a string.
"%xxxx%" is telling SQL that the search string can appear anywhere in the titulo column. '%' is a wildcard in SQL.
%w{xxx yyy zzz} is shorthand for ["xxx", "yyy", "zzz"] - an array in Ruby, which wouldn't mean much to the SQL as a string by itself.

Don't include current user in Pluck array

I have a form where a user can CRUD a task and assign it to another user via the form. I currently am using the pluck method to get the full array of users. Naturally, I want to exclude the current user from this list.
My current code in task > _form.html.erb is as follows:
<%= f.select :assignee, User.pluck(:email), :prompt => "Select one" %>
It's difficult to figure out what to do since User.pluck(:email) provides a full array that is hard to exclude values from. Appreciate any suggestions, ideally that can be done in this field rather than in the controller.
Thanks!
You can do this by using where and passing conditions to exclude the current_user
<%= f.select :assignee, User.where("id <> ?", current_user.id).pluck(:email), :prompt => "Select one" %>
You could add a where condition:
<%= f.select :assignee, User.where('id != ?', current_user.id).pluck(:email), :prompt => "Select one" %>

Resources