I am building a toy Rails app. I generated a scaffold for my Post objects. Now, I want to add some search functionality to the scaffold generated view. I am following http://railscasts.com/episodes/37-simple-search-form to add the search functionality.
To app/views/posts/index.html.erb I add
<% form_tag posts_path, :method => 'get' do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>
and then the code for listings follow.
In controllers/posts_controller.rb I have
class PostsController < ApplicationController
# GET /posts
# GET /posts.json
def index
@posts = Post.search(params[:search])
respond_to do |format|
format.html # index.html.erb
format.json { render json: @posts }
end
end
In model/post.rb I have
class Post < ActiveRecord::Base
attr_accessible :description, :image_url, :title
validates :name, :presence => true
validates :title, :presence => true,
:length => { :minimum => 5 }
def self.search(search)
if search
find(:all, :conditions => ['name LIKE?', "%#{$search}%"])
else
find(:all)
end
end
end
When I run the server, I don’t get any errors, but the form doesn’t show up. I looked at the generated page source, and there is no form there. What is going on? Is there a way to debug situations like these?
Since Rails 3 the
form_taghelper itself return the html it produces. The equal sign is needed. So please change the first line toThat was different in Rails 2. As the railscasts episode is quite old you may run into other issues as well.
See the Rails API as well.
Good luck.