我制作了一个搜索(过滤)表单来根据给定值过滤我的对象。有一个公司模型,搜索将根据其属性。这是我的 index.html.erb:
<% provide(:title, 'All companies') %>
<h1>All companies</h1>
<%= form_tag companies_path, :method => 'get' do %>
<%= hidden_field_tag :direction, params[:direction] %>
<%= hidden_field_tag :sort, params[:sort] %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>
<table class="pretty" border="1" cellpadding="10">
<tr>
<th><%= sortable "name" %></th>
<th><%= sortable "city" %></th>
<th><%= sortable "country" %></th>
<th><%= sortable "street_address" %></th>
<th><%= sortable "sector" %></th>
<th><%= sortable "telephone" %></th>
<th><%= sortable "fax" %></th>
<th>DELETE</th>
</tr>
<% for company in @companies %>
<tr class="<%= cycle('oddrow', 'evenrow') -%>">
<td><%= link_to company.name, company %></td>
<td><%= company.city %></td>
<td><%= company.country %></td>
<td><%= company.street_address %></td>
<td><%= company.sector %></td>
<td><%= company.telephone %></td>
<td><%= company.fax %></td>
<td><% if current_user.admin? %>
|| <%= link_to "delete", company, method: :delete,
data: { confirm: "You sure?" } %>
<% end %></td>
</tr>
<% end %>
</table>
<%= will_paginate @companies %>
这是我的 company_controller.rb
helper_method :sort_column, :sort_direction
def index
@companies = Company.search(params[:search]).order(sort_column + ' ' + sort_direction).paginate(:per_page => 10, :page => params[:page])
end
这是我的模型公司.rb
class Company < ActiveRecord::Base
attr_accessible :city, :country, :fax, :name, :reseller, :sector, :street_address, :telephone, :id
has_many :users , dependent: :destroy
def name_for_form
"#{name}"
end
def self.search(search)
if search
q = "%#{search}"
where('name LIKE ? OR city LIKE ? OR country LIKE ? OR street_address LIKE ? OR telephone LIKE ? OR fax LIKE ? OR sector LIKE ?',
q,q,q,q,q,q,q)
else
scoped
end
end
validates :city, presence: true
validates :country, presence: true
validates :fax, presence: true
validates :name, presence: true
validates :sector, presence: true
validates :street_address, presence: true
validates :telephone, presence: true
end
假设我有 3 家公司,分别名为 kalahari、kalahari 2 和 kalahari2。当我搜索 kalahari 时,它只找到 1 家公司,kalahari。我的意思是它在 kalahari 2 或 kalahari2 中找不到 kalahari。只找到完全匹配。当我搜索 kala 时,它什么也没找到。我怎样才能最简单地解决这个问题?我是 Rails 新手,不想搞砸很多事情。