作为ruby-on-rails初学者,我正在创建一个非常简单的应用来测试搜索表单。这就是一切:
class Person < ActiveRecord::Base
def self.search(search)
if search
all(:conditions => ['name LIKE ?', "%#{search}%"])
else
all
end
end
end
class PersonsController < ApplicationController
def index
@person = Person.search(params[:search])
end
end
<h1>Persons#index</h1>
<%= form_tag persons_index_path, :method => 'get' do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
&lt;%end%&gt;
<div>
<% @person.each do |person| %>
<p><%= person.name %><p>
<% end %>
</div>
当我加载索引并使用搜索表单时,我收到此错误:
错误的参数数量(1表示0)
提取的来源(第5行): 3 4 五 6 7 8
def self.search(search)
if search
all(:conditions => ['name LIKE ?', "%#{search}%"])
else
all
end
毫无疑问我犯了一个简单的错误,有什么建议吗?
答案 0 :(得分:1)
将搜索方法更改为:(缩小版)
def self.search(search)
search.present? ? where('name LIKE ?', "%#{search}%") : all
end
或您的旧方法:(您的旧结构)
def self.search(search)
if search.present?
where('name LIKE ?', "%#{search}%")
else
all
end
end