我在数据输入之前执行搜索,以确保用户不重复现有条目,并且无法识别如何捕获和使用搜索结果数量引导用户进入下一步。需要识别搜索返回的项目数
我使用的轨道3和pg_search宝石
型号/ request.rb
class Request < ActiveRecord::Base
attr_accessible :description, :title, :user_id, :who
belongs_to :user
has_many :comments
include PgSearch
pg_search_scope :search, against: [:title, :description, :who],
using: {tsearch: {dictionary: "english"}},
associated_against: {user: :name},
ignoring: :accents
def self.request_search(query)
if query.present?
search(query)
where("title @@ :q or description @@ :q or who @@ :q", q: query)
else
scoped
end
end
end
requests_controller.rb
def index
@requests = Request.request_search(params[:search]).order(sort_column + " " + sort_direction).paginate(:per_page => 4, :page => params[:page])
@users = User.all
end
- 开始编辑(每杰西的答案)
requests_controller.rb(续)
private
def sort_column
Request.column_names.include?(params[:sort]) ? params[:sort] : "title"
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end
application_helper.rb
def sortable(column, title = nil)
title ||= column.titleize
css_class = column == sort_column ? "current #{sort_direction}" : nil
direction = column == sort_column && sort_direction == "asc" ? "desc" : "asc"
link_to title, params.merge(:sort => column, :direction => direction, :page => nil), {:class => css_class}
end
_requests.html.erb(局部的)
<%= hidden_field_tag :direction, params[:direction] %>
<%= hidden_field_tag :sort, params[:sort] %>
<div class="row">
<table class="table table-striped pretty">
<thead>
<tr>
<th><%= sortable "title" %></th>
<th><%= sortable "who", "Requested Pro" %></th>
<th><%= sortable "created_at", "When" %></th>
<th><%= sortable "request.user", "Requested by" %></th>
</tr>
</thead>
<tbody>
<% @requests.each do |request| %>
<tr>
<td><%= request.title %></td>
<td><%= request.who %></td>
<td><%= request.created_at %></td>
<td><%= request.user.name %></td>
<td><%= link_to 'Show', request, :class => 'btn btn-mini'%></td>
<% if can? :update, @course %>
<td><%= link_to 'Edit', edit_request_path(request) %></td>
<td><%= link_to 'Destroy', request,
confirm: 'Are you sure?',
method: :delete,
:class => 'btn btn-mini' %></td>
<% end %>
</tr>
<% end %>
</tbody>
</table>
<div class="pull-right"><%= will_paginate @requests %></div>
</div>
<%= button_to 'New Request', new_request_path, :class => 'btn btn-large btn-primary mleft20 mtop20' %>
- 端编辑
例如,有两种方法可以在到达来自其他页面的索引页面,搜索之后或通过链接。如果用户在搜索后到达索引,我想在搜索结果的前面插入一些文字,说:您的搜索产生了“x”项。如果您没有看到要查找的内容,请点击按钮输入新请求。
否则,如果用户刚刚链接到索引,我希望能够隐藏文本并只显示索引。
我想我可以通过request_search以某种方式访问搜索属性(如果它是正确的调用它),但我不知道如何在视图中执行它(几次尝试后)。
其次,如果我能加入,我期待在搜索文本复制到如果用户决定创建新条目进入的领域之一......
请让我知道如果我说了问题清楚,如果你能为我提供一些亮光。提前致谢。
(我假设你在这里使用will_paginate进行分页) –
嘿,杰西。感谢您的及时回复。编辑该问题以包含相关的排序方法,并根据您的建议在视图中查找will_paginate。 –
当用户通过搜索到达页面时,您的答案很有用(并且足以让我休息)。仍在研究当用户通过链接到达时会发生什么。现在,当通过链接到达时,您的解决方案返回零个项目,因为没有搜索参数,即没有搜索。很确定我可以通过路由到不同的着陆页并使用相同的部分来处理第二种情况。在我能够解决问题后发布。再次感谢。 –