views:

349

answers:

1

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!

+1  A: 

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.

jdl
Thanks. Didn't realize the formatting got out of whack. So, in my view, I can put the following, correct? <h1>Businesses in <%=h @search %></h1>. But I'm not sure what to do after the @search part.
MikeH
The view code looks fine. I'm not sure what you're getting at with "But I'm not sure what to do after the @search part" though.
jdl
Thanks, jdl. My earlier comment was wrong. I screwed up when implementing your instructions, but your solution worked.
MikeH