2012-05-22 75 views
0

我正在構建玩具Rails應用程序。我爲我的Post對象生成了一個腳手架。現在,我想添加一些搜索功能到腳手架生成的視圖。我在關注http://railscasts.com/episodes/37-simple-search-form添加搜索功能。搜索表單不顯示

到App /人次/職位/ index.html.erb我添加

<% form_tag posts_path, :method => 'get' do %> 
    <p> 
    <%= text_field_tag :search, params[:search] %> 
    <%= submit_tag "Search", :name => nil %> 
    </p> 
<% end %> 

,然後列表中的代碼。

在控制器/ posts_controller.rb我

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 

在模型/ post.rb我

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 

當我運行服務器,我沒有得到任何錯誤,但表單不顯示。我查看了生成的頁面源代碼,並且沒有表單。到底是怎麼回事?有沒有辦法來調試這些情況?

回答

2

由於Rails 3 form_tag幫助器本身返回它產生的html。等號是必需的。所以,請在第一線更改爲

<%= form_tag posts_path, :method => 'get' do %> 

是Rails 2不同,因爲railscasts情節是很老,你可能會遇到其他一些問題。

另請參閱the Rails API

祝你好運。