代码在我的产品型号(product.rb):Rails 3中,简单的搜索问题
def self.search(search)
if search
find(:all)
else
find(:all)
end
end
代码在我的搜索控制器(search_controller.rb):
def index
@products = Product.search("Apple")
end
代码在我看来, (index.html.erb):
<h1>Products</h1>
<% form_tag client_search_path , :method => :get do %>
<p>
<%= search_field_tag :term, params[:term], :class=> "auto_search_complete"%>
<%= submit_tag "Search", :name => nil, :class => 'button', :id => "search_bn" %>
</p>
<% end %>
<table border="1px">
<tr>
<th>Name</th>
<th>Brand</th>
<th>Quantity available</th>
<th>Category</th>
<th>Shopcenter name</th>
<th>Shopcenter streetnumb</th>
<th>Shopcenter streetname</th>
<th>Shopcenter postal</th>
<th>Shopcenter province</th>
</tr>
<% for product in @products%>
<tr>
<td><%= product.name %></td>
<td><%= product.brand %></td>
<td><%= product.quantity_available %></td>
<td><%= product.category %></td>
<td><%= product.shopCenter_name %></td>
<td><%= product.shopCenter_streetNumb %></td>
<td><%= product.shopCenter_streetName %></td>
<td><%= product.shopCenter_postal %></td>
<td><%= product.shopCenter_province %></td>
</tr>
<% end %>
</table>
我打开这一切都很好,但如果我评论在我的模型代码行之一:
def self.search(search)
if search
#find(:all)
else
find(:all)
end
end
我希望这至少可以用于最初的渲染,或者当我提交一个空的搜索术语,但它不是。和更改代码的模式来:
def self.search(search)
if search
find_all_by_name(search)
else
find(:all)
end
end
不工作,它给了我一个错误的观点正在与一个零对象,这是不可能的,因为我的数据库中有条目。
有人可以解释发生了什么?我的印象是我的模型中的两个条件都被执行了。至少这就是每个案例中的2个陈述向我展示的。 请指教。
在控制器@products = Product.search( “苹果”)应该是 @products = Product.search(params [:term])和 之前,如果执行if, search = nil if search ==“” – Rafal 2011-02-10 16:52:52