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.
Related
I am trying to implement a search field in Rails 4 to find data behind two models. I have two controllers: buildings and rooms, and two models: building and room. A building, naturally, has many rooms and a room belongs to a building, which I have stated in the respective models.
Basically, a user could type either a building or a room name into the search form and it would return a response with details about the building or room. Of course, a building needs to have an address, and a room needs to know in which building it is with the address as well. So I'd need to display different details according to the searched for instance. Both have the same String attribute name, so this could make things easier.
I have no luck in finding a relevant example on how to implement such a search form. This is the working basic search I have at the moment in views\buildings\index.html.erb, which can only search buildings:
<%= form_tag({controller: "buildings", action: "show"}, method: "get", class: "nifty_form") do %>
<%= label_tag(:name, "Search for a building (later also rooms):") %>
<%= text_field_tag(:name) %>
<%= submit_tag("Search") %>
<% end %>
This is the show method in controllers\buildings_controller.rb:
def show
#building = Building.where('lower(name) = ?', params[:name].downcase).first
end
And this is the route it refers to:
get 'buildings/:id' => 'buildings#show'
Any and all help is appreciated!
I would recommend you to add the search code in the index method of buildings controller, there are many things you can do but here is what i will recommend:
def index
#
if params.has_key?(:name)
#buildings = Building.joins(:rooms).
where([
'lower(buildings.name) like ? or lower(rooms.name) like ?',
"%#{params[:name].downcase}%",
"%#{params[:name].downcase}%"
])
else
# your normal code goes here.
end
end
Any other information you need such address ( is that a different model ) can he included in there.
Hope this helps,
PD: if necessary you can render a different view when a search is present inside your if block
render action: 'my_custom_view', status: :ok
Due to time restrictions, I decided to merge these models into one common model, Space. It holds all the information that a building and a room needs. Thanks anyways!
I'm new to Rails so be gentle. I've got a model, 'Event', with the the following information: 'sport', 'home_team', 'away_team', and 'time' in datetime.
Now I want to enable the user to 'follow' a specific event and am trying to find the best way to do so. Ideally, I'd like a form with dependent drop down lists. For example, the user first picks a 'day', then a 'sport', then selects from a relevant list of 'events' of that 'day' and 'sport'. This association is then stored in a rich join table called 'following'.
I've seen tutorials on complex forms that involve multiple models, but what about when everything is from the same model? How do build a form to grab a handful of relevant records. I only have a few distinct values for 'sport', so I wasn't sure it made sense to give it its own model. And can I easily get events on a certain date from a 'datetime' value?
There a lot of ways to go about this, here is one option:
Since you want to see multiple events, you'd probably start off focused on the index action. Start off by creating and index action, but add some hooks to filter it, i.e.
def index
if params[:sport]
#events = Event.where("sport = ?",params[:sport])
else
#events = Event.all()
end
end
Now, if you've defined your routes like this:
resources :events
You'll have a a route /events that will accept a get request and route you to the index action.
But if you want a form where you can select things, a form will by default POST, but you could create a form that GETs to '/events'
i.e. in app/views/events/index.html.erb
<%= form_tag '/events', :method=>:get %>
Then, you want to create your form elements that will send the params.
i.e.
<%= select_tag 'sport', '<option>baseball</option><option>football</option>' %>
Put in a submit button
<%= submit_tag 'See Events'
Then 'end' your form with
<% end %>
Now when you click on the 'See Events' button, you will send a get request to the route '/events', and the 'sport' parameter will show up in the index action, filtering the events.
To keep things simple and all in the index view, after your form you'd list all the events.
<% #events.each do |e| %>
Sport: <%= e.sport %><br/>
Home Team: <%= e.home_team %><br/>
Away Team: <%= e.away_team %><br/>
Time: <%= e.time.strftime('%H %M') %><br/>
<% end %>
I am attempting to create a search form, the search is performed on third party site so there is no model just a controller. I have it set up as follows
views/items/index.html.haml :
= search_field :search, :search_input
= submit_tag 'Search'
views/items/search.html.haml:
-#items.each do |item|
%h1= item.title
controllers/items_controller.rb:
def index
#I am unsure of what to put in here? I think
#I need something wich sends #search_input to my search method
end
def search
#items = some_third_party_search_method_i_wrote{ params[:search_input]}
end
How does one properly use the params object in rails? I don't understand how to get from the index page containing the search form to the search page containing the results of the search input?
You probably want to use search_field_tag instead since your form isn't tied to a model/object:
= search_field_tag :search_input
Then params[:search_input] should work.
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.