I've managed to build a simple search model and have four attributes that can be searched; name, age, location and gender. The problem I am having is I can't seem to find the right code to search multiple attributes.
For example a search for "adam" should produce all users named adam, whereas a search for london should display all users from london. I can only search one attribute individually (name) so if I type in "london" it displays a blank result page.
/people/index.html.erb (search form)
<%= form_tag people_path, :method => 'get' do %>
<%= text_field_tag :search, params[:search]%>
<%= submit_tag "Search" %>
<% end %>
models/person.rb
class Person < ActiveRecord::Base
attr_accessible :age, :gender, :location, :name
def self.search(search, id)
if search
where(['name LIKE ?', "%#{search}%"])
else
scoped
end
end
end
people_controller.rb
def index
#people = Person.search(params[:search], params[:id])
end
The following code worked fine.
where('name LIKE ? OR location LIKE ?', "%#{search}%","%#{search}%")
#meagar, I fail to understand how that simple line of code "is outside the scope of Stack Overflow".
You can checkout Sunspot_rails gem for your problem, it integrate Solr search engine platform into Rails and is a battle proved solution for Rails app. In my company's website Fishtrip.cn we use solr to search for both House, Transportation retailer and tours. It might be a little bit heavy for your project, but if are looking for a powerful solution then Sunspot definitely would be one of it.
Related
I am trying to have two search fields, that however end up combining the two results.
In one filed you can search for the location of a listing and in the other for a keyword, which will look for title and description of the listing.
When a location and keyword is entered, listings that match both the location and keyword should show. So if I enter San Francisco and Retail, only listings located in SF and with the description or title Retail should pop up.
Feng Chen suggested to do this in one query by the following:
self.where("location like ? and (title like ? or description like ?)", query, query)
However this does not show a result that matches both the location and the keyword(title, description).
Do I need to change something in my view or anywhere else?
Here is what I have listing.rb
def self.locsearch(search)
query = "%#{search}%"
if search
self.where("location like ? and (title like ? or description like ?)", query, query)
else
self.all
end
end
end
Static_pages_controller.rb
def home
#listings = #listings.locsearch(params[:search]) if params[:search].present?
home.html.erb
<%= form_tag findjobs_path, :controller => 'listings', :action => 'locsearch', :method => 'get' do %>
<p>
<%= text_field_tag :search, "location" %>
<%= text_field_tag :search, "keyword" %>
<%= submit_tag "search" %>
</p>
</div>
<% end %>
You need a descsearch method in your listing model and you need to do
# Right now you have #listings = #listings.locsearch(...)
# You need #listings = Listing.locsearch(...)
#listings = Listing.locsearch(params[:search][:location], params[:search][:keyword])
And in your listing model
def self.locsearch(location, keyword)
location = "%#{location}%"
keyword = "%#{keyword}%"
if !location.bllank? && !keyword.blank?
self.where("location like ? and (title like ? or description like ?)", location, keyword)
else
self.all
end
end
end
If you are using a postgres database, you could try to use the full text search feature to do the above. There is gem pg_search enter link description herewhich will allow you to do so easily. The overhead incurred would be trivial and would provide you greater flexibility in this search problem and any such other ones you might have to solve later.
My party registry Rails 3 app needs a search function for visitors to search a partyname and then be able to click on the party and go to the show page of that party. Must be very simple ajax list that pops up without reloading etc.
The app is almost done and runs off a sqlight3 database.
Any suggestions - tried all the RailsCasts ones and nothing fits right 100%.
Thanks in advance.
I think you want two different things.
1) To create a simple search you can do something like this.
2) To autocomplete while typing (partyname for example) you can use the autocomplete gem.
You must decide which approach you want to follow.....
I hope if helps in some way...
EDIT - to show how to implement the simple search.
let's say you have a model called Party
your form (index page for example):
...
<%= form_tag parties_path, method: :get do %>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", name: nil %>
<% end %>
...
#display results
<% #parties.each do |party| %>
...
<% end %>
model Party:
...
def self.search(search)
# if search is not empty
if search
find(:all, :conditions => ["partyname LIKE ?", "%#{search}%"])
# if search is empty return all
else
find(:all)
end
end
...
controle parties_controller:
#parties = Party.search(params[:search])
Try smart_search gem
gem install smart_search
Does everything that needs to be done to make your model searchable!
I want users to be able to use one search box to search for different objects. I would differentiate them on the results page. Both would be full text search.
Should I make a Search controller and load everything into the index action with something like:
#posts = Post.all
#groups = Group.all
Something tells me that would be fantastically inefficient.
I'm not really sure where to start, I haven't managed to find anything addressing this question on the interwebs, but if I have overlooked something let me know.
Thanks
EDIT:
here's my search bar that is available globally on my website:
-form_tag posts_path, :method => :get do
=text_field_tag :search, params[:search], :id => 'searchfield'
=submit_tag '',:name => nil, :id => 'searchbutton'
it only searches the "Post" model right now, and displays the results on the Post#index view
I want to be able to have queries typed into the search box be searched for in both the Post and Group tables, and the results be displayed in two separate columns on the same page. maybe through a search controller/view
If you want to search both types at once, you can use this form:
# Pass your models in by class constant
Sunspot.search(Post,Group) do |s|
s.fulltext(params[:search])
end
This is documented in the wiki:
https://github.com/sunspot/sunspot/wiki/Working-with-search#initiating-a-search
Add the searchable directive from sunspot solr to your models for indexing. For example:
class Post < ActiveRecord::Base
searchable do
text :title, :body
end
end
class Group < ActiveRecord::Base
searchable do
text :name
end
end
If you have existing data in DB make sure to run rake sunspot:solr:reindex for indexing. For new data the indexing will be done in a hook.
Now you can search:
#posts = Post.search {fulltext params[:search]}
#groups = Group.search {fulltext params[:search]}
Now you have the data for your two columns.
This is not the answer, but I found something useful. It is a gem that helps you searching across multiple tables:
https://github.com/toptierlabs/acts_as_fulltextable.
It helps you keeping all the searchable data (from different models) in one place.
I'm creating an application that tracks users and achievements (think, xbox live, etc.) These tables are linked via a join table. I would like to have a search form on my index that lets users type in a users name and a new page is loaded with a list of all achievements that user has earned. I'm not entirely sure how to set up this search form, on the index, to actually search the user table and return the results on a new page. Any help would be greatly appreciated. If you require more information then I'll be happy to provide it.
Here's a bit of skeleton code to get you started based off what I think you need from what you have said. I hope this is useful.
For the search bit you could do something like this in your index view:
<%= form_for User.new, :url => "search" do |f| %>
<%= f.label :name %>
<%- f.text_field :name %>
<%- end %>
In your controller:
def search
q = params[:user][:name]
#users = User.find(:all, :conditions => ["name LIKE %?%",q])
end
and in your search view:
<%-#users.each do |user| %>
Name: <%=user.name %>
<%- user.achievements.each do |achievement| %>
<%= achievement.name %>
<%- end %>
<%- end %>
You would, of course, need to ensure the users and achievement models are correctly linked:
class User << ActiveRecord::Base
has_many :achievements
end
There are plenty of tutorials and things about this e.g.:
http://blog.devinterface.com/2010/05/how-to-model-a-custom-search-form-in-rails/
Look the thing is every basic explanation in Rails3 starting with the Initial Tutorial provided by them explains you how to setup a new Controller/Model. The example was only one of thousands explaining the same problem.
It is a very broad range of different things you can do to achieve this. Basically you have to put some code in the controller:
which handles the search (including the activerecord stuff or whichever technique you use to access your model)
which sets some variables necessary for the search form
Setup two routes etc... Its to broad and completely covered even by the basic official rails3 tutorial.
Here is an application based on searchlogic is very useful and you can search by whatever you want
https://github.com/railscasts/176-searchlogic
You may want to check out the Ransack gem. https://github.com/activerecord-hackery/ransack
I built a basic search form that queries one column in one table of my app. I followed episode 37 Railscast: http://railscasts.com/episodes/37-simple-search-form
Here's my problem. I want to display the search query that the user makes in the view that displays the search results. In my app, the search queries the zip code column of my profile model, and returns a list of profiles that contain the right zip code. On the top of the list of profiles returned from the search, I want it to say "Profiles located in [zip code that was queried]."
I'm sure I can do this because the queried zip code gets passed into the url displaying the results. So if the url can pick it up, there must be some way to display it in the view on the page as well. But I don't how.
Please keep in mind that I'm not using any search pluggins and I don't want to use any for now. This is my first app, so I don't want to add complexity where it's not needed.
Per Ryan's instructions in the Railscast, here's my setup:
PROFILES CONTROLLER
def index
#profiles = Profile.search(params[:search])
end
PROFILE MODEL
def self.search(search)
if search
find(:all, :conditions => ['zip LIKE ?', "%#{search}%"])
else
find(:all)
end
end
PROFILE/INDEX.HTML.ERB
<% form_tag ('/profiles', :method => :get) do %>
<%= text_field_tag :search, params[:search], :maxlength => 5 %>
<%= submit_tag "Go", :name => nil %>
<% end %>
The search itself is working perfectly, so that's not an issue. I just need to know how to display the queried zip code in the view displaying the results.
Thanks!
Just set it to an instance variable and use that.
def index
#search = params[:search]
#profiles = Profile.search(#search)
end
In your view, you can reference #search.
Also, as a friendly tip, please use an indent of 2 spaces for Rails code. It's the standard way to do it, and others who are reading your code will appreciate it.