0

我在 Rails 中有一个简单的搜索:

def self.search(search)
# if search is not empty
if search
find(:all, :conditions => ["name LIKE ?", "%#{search}%"])
# if search is empty return all
else
find(:all)
end

风景:

<% if @registries.empty? %>
Can't find the registry. Please try a differnet name.
<% else %>
<% @registries.each do |registry| %>
 ......etc.

如果找不到查询,我如何对其进行编码以显示“Nothing Found”而不是 find(:all)?

我尝试了一些东西,但没有任何效果。即使我取出 else 它仍然会显示所有查询,如果它找不到要搜索的那个。

提前致谢

4

1 回答 1

1

当您的意思是“不为空”时,您必须专门针对它进行测试。请记住,在 Ruby 中只有两个值为 false 的值:falsenil.

您可能打算:

if (search.present?)
  where("name like ?", "%#{search}%").all
else
  all
end

使用 Rails 3 样式where子句使您的方法更容易理解。使用findwith:conditions是旧的 Rails 1 和 2 风格。

于 2012-06-28T14:09:51.577 回答