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.
Related
I'm new to RoR and I've managed to make a basic search form but keep getting errors when trying to expand the search tags (name).. I have a model with various data (location, website, email, telephone) and was wondering how I can add these to my current search code.
/models/ciir.rb
def self.search(search)
if search
find(:all, :conditions => ['name LIKE ?', "%#{search}%"])
else
find(:all)
end
end
static_pages_controller.rb
def home
#ciirs = Ciir.search(params[:search])
end
/home.html.erb
<%= form_tag ciirs_path, :method => 'get' do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag " Search Database Records ", :name => nil %>
</p>
<% end %>
When clicking the submit button (no search terms) the url is:
ciirs?utf8=✓&search=
but when modifying the name condition to something like 'website' the url changes to
ciirs?utf8=✓&search=&commit=+Search+Database+Records+ –
Since you mentioned you are new to RoR, I must share the way I learned RoR was reading, using and analyzing one issue at a time. I would suggest you to take a look at following points one at a time and try & learn how RoR treats them and how these fit your question:
How form_tag works?
How text_field_tag works?
Once you have understood form_tag, difference between text_field_tag and f.text_field?
How params objects are created, and it uses names of form controls?
How and when to use GET and/or POST form methods? Inadvertently, what are different types of method and when to use them?
How URL are used in the form_tag and what components are they made of?
Sprinkle a bit of knowledge of Ruby language by learning between Arrays and Hashes? In fact, learn Ruby as much as you can.
Answering your question,
/home.html.erb
<%= form_tag "/static_pages/home", :method => 'post' do %>
<p>
<%= text_field_tag "search[name]", params.has_key?("search") && params[:search].has_key?("name") ? params[:search][:name] : "" %>
<%= submit_tag " Search Database Records " %>
</p>
<% end %>
/models/ciir.rb
def self.search(search)
if search
find(:all, :conditions => ["name LIKE '%?%'", search[:name]])
else
find(:all)
end
end
So I modified your form, and told RoR about search params containing data for name.
params is a Hash (which is a key-value pair) having key named search, which further is a Hash having key named name.
The same principle is followed in the model code. We passed the Hash of key search to the function and in there, used the value of key named name.
I also updated the url in form_tag, to point it to home action of your controller. Assuming that you have added it to your routes.rb file, it usually follows the pattern controller_name/action_name or the function name action_name_controller_name_path or action_name_controller_name_url. Run rake routes command at your root directory to list out all paths in your application.
Also note, I used POST method instead of original GET. You may wish to use GET here, so please change it back.
I hope this works.
I found no error in your code. the url changed to ciirs?utf8=✓&search=&commit=+Search+Database+Records+ is normal. submit_tag generates a button named "commit" defaultly, it will be parsed in the params. I see you add :name => nil , it will fix the problem, the other part of your code needn't to be modified. I copied your code and tested it, it ran smoothly.
I'm trying to put a quick keyword search in my navbar, using Bootstrap's Navbar Search component. Currently this is using a form_tag as follows
<form class="navbar-search pull-left">
<%= form_tag(recipes_path, :method => :get) do %>
<%= text_field_tag :keywords, nil,
{:class => "search-query", :placeholder => "recipes quick search"} %>
<%= hidden_field_tag :use_keywords, "true" %>
<%= hidden_field_tag :wide_search, "true" %>
<% end %>
</form>
This is for a recipe lookup. I'm using the form to (try to) get keywords, which will be passed as params to the search, which resides in the recipes index action.
def index
if params[:wide_search].present?
#search = Search.new
#search.use_keywords = params[:use_keywords]
#search.keywords = params[:keywords]
... (more params for other search types)
if params[:wide_search] == "true"
#recipes = #search.wide_search
elsif params[:wide_search] == "false"
#recipes = #search.narrow_search
end
#recipes = #recipes.paginate(:page => params[:page])
else # no params, just index all
#recipes = Recipe.paginate(:page => params[:page])
end
end
Note that "Search" is a ruby class. I was thinking of making it into a full-blown resource so I could create and view old searches (maybe they could be looked at to offer suggested searches based on past history, etc), but decided against it. I still dunno if that was a good idea or not. If it was an actual resource, it could have RESTful actions and maybe save some problems. This is not my actual problem, but does anyone have suggestions for this?
Sorry, back to the actual problem -- From the root page or wherever, I would like to be able to type in keywords, press the enter key (within the search bar) and have it redirect to the Recipe Index with the params needed so it can run the search and display the results.
Right now, if I go to the index page and do this, it works fine. BUT, if I'm in any other page (like the root page, or wherever) and try to type keywords and press enter, it just reloads the current page, although I do see the params in the URL. So it's not redirecting to Recipe Index. I must be missing something, but I'm not sure what. I'm kind of suspicious of the form_tag since there's no actual submit button. But then it works when I'm in the index page, so I dunno. Any suggestions appreciated!
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 am working a simple rails app and i would like to know how possible it is to use one search form to search inside multiple models. like i have a story model and a book model. this search form should be able to search the both models with a single parameter.
<%= for_tag :url => search_path %>
<%= text_field_tag :q %>
<% end %>
How can i make this search from work for multipple models
Whatever search you need to do, is done inside an action in a controller. You could basically create a controller, say search_controller and have an action say, item
def item
if params[:q]
#found_stories = Story.find_all_by_...(params[:q])
#found_books= Book.find_all_by_...(params[:q])
end
end
Then you could use the objects #found_stories and #found_books in your view to show the search results.
This is just an example of how you could do to fulfill your requirement.
Thanks.
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