2013-05-12 46 views
0

我正在使用rails应用程序,其中我创建了一个表产品名称:string和Number:integer。通过Http在rails中查询数据库?

如果产品存在,应用程序应该为用户提供一个可以通过他的编号搜索产品的表单,它应该从数据库提供产品名称。

我的search.html.erb是这样的。

<%= form_for @products, :url => { :action => "create" }, :html => {:class => "nifty_form"} do |f| %> 
    <%= f.text_area :number, :size => "60x12" %> 
    <%= f.submit "Search" %> 
    <% end 

什么是ProductController中搜索方法的定义和我需要在routes.rb中添加的路线?

回答

1

的极好形式没关系,这是我怎么会做这样的:


config/routes.rb

resources :products do 
    post 'search', :on => :collection 
end 

这会给我一个search_products_path

您认为更换resources :products'

<%= form_for(:search, :url => search_products_path) do |f| %> 
    <%= f.text_field :number, :placeholder => "Enter number to search" %> 
    <%= f.submit "Search" %> 
<% end %> 

在您的products_controller.rb

def search 
    number = params[:search][:number] 
    @result = Product.find_by_number(number) 
    @not_found = true unless @result 
end 

在你views/products/search.html.erb,使用@result,以显示产品信息;在检查期望的产品是否被实际找到时要小心。如果它不存在,我已经设置了boolean @not_found。

+0

我在搜索页面出现此错误。无法找到产品id = search – 2013-05-12 13:07:13

+0

将控制器操作传递给'search.html.erb'后? – kiddorails 2013-05-12 13:08:38

+0

更新所有建议的文件,然后导航到产品/搜索后,出现此错误。 – 2013-05-12 13:12:35