我有一個應用程序,允許用戶輸入,編輯和搜索數據庫中的項目。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