我有一个应用程序,允许用户输入,编辑和搜索数据库中的项目。Ruby on Rails:用布尔搜索 - postgres
在我的搜索功能中,您可以通过向搜索添加参数来执行复杂搜索。
def self.like(text); "%#{text}%"; end
def self.search(search_archive, search_client, search_status, search_fullname)
# start with a scoped query, to apply more scopes on it afterwards
_projects = Project.scoped
# then, for each of the parameters, apply the scope only if present
if search_archive.present?
_projects = _projects.where ['archive LIKE ?', like(search_archive)]
end
if search_client.present?
_projects = _projects.where ['client LIKE ?', like(search_client)]
end
if search_status.present?
_projects = _projects.where ['status LIKE ?', like(search_status)]
end
if search_fullname.present?
_projects = _projects.where ['fullname LIKE ?', like(search_fullname)]
end
# now you have applied only the present scopes. return the result, and watch
# the query as it executes.
_projects
end
现在我最近添加了选项来存档项目,该项目作为布尔值进入项目表。
我知道我的搜索功能是错误的,因为我不认为我可以用他们尝试过的方式处理布尔值。
以下是错误:
PG::Error: ERROR: operator does not exist: boolean ~~ unknown
LINE 1: SELECT COUNT(*) FROM "projects" WHERE (archive LIKE '%{"{:c...
任何想法?提前致谢。
UPDATE:
更改为下面的建议,
if search_archive.present?
_projects = _projects.where(:archive => search_archive)
end
我得到这个错误:
PG::Error: ERROR: missing FROM-clause entry for table "archive"
LINE 1: SELECT COUNT(*) FROM "projects" WHERE "archive"."{:class=>"...
^
: SELECT COUNT(*) FROM "projects" WHERE "archive"."{:class=>""archive""}" = '1'
这里是我的搜索行动:
搜索视图的附加部
<%= form_tag search_path, method: :get do %>
<% if current_user.try(:admin?) %>
Archive:
<%= check_box :archive, :class => "archive" %></H2>
<% end %>
<% if !current_user.try(:admin?) %>
<%= hidden_field :archive, :value => false %>
<% end %>
<div class="client">
Client :
<%= select(@projects, :client, Project.order("client").map{|p| [p.client]}.uniq, :prompt => "-Any-", :selected => params[:client]) %></br>
</div>
<div class="buttons">
<div id="search_button">
<%= submit_tag "Search", name: nil, :class => "button" %>
</div>
<% end %>
说明
如果我是管理员,我将存档复选框选中,我想看看是不是所有的项目存档。如果我检查它,我只想看看存档的,包含在我搜索的其他参数中。
如果我是普通用户,我不应该能够看到归档复选框,并且我所做的每个搜索都应该放在归档为false的项目后面。
我已添加我的搜索视图。我需要根据用户是否是admin来搜索真或假。 – Jazz
@jazz: - 检查我的更新回答 – Salil
谢谢,似乎工作。然而,我需要每一个搜索总是搜索'归档'为假,除非这个盒子是票。因此,为什么只有管理员可以看到归档文件,并且没有任何管理员永远不会看到它们,因为他们所做的每个搜索都始终搜索“归档”为假 – Jazz