ユーザーがデータベース内のプロジェクトを入力、編集、検索できるアプリがあります。
私の検索機能では、検索にパラメーターを追加することで複雑な検索を行うことができます。
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
最近、プロジェクトをアーカイブするオプションを追加しました。これは、ブール値としてプロジェクト テーブルに入ります。
私が試した方法でブール値を処理できるとは思わないため、検索機能が間違っていることはわかっています。
if search_archive.present?
_projects = _projects.where ['archive LIKE ?', like(search_archive)]
end
エラーは次のとおりです。
PG::Error: ERROR: operator does not exist: boolean ~~ unknown
LINE 1: SELECT COUNT(*) FROM "projects" WHERE (archive LIKE '%{"{:c...
何か案は?前もって感謝します。
アップデート:
以下の提案に変更すると、
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'
これが私の検索アクションです:
def search
@search = params[:archive], params[:client], params[:status], params[:fullname]
@project_search = Project.search(*@search).order(sort_column + ' ' + sort_direction).paginated_for_index(per_page, page)
@search_performed = !@search.reject! { |c| c.blank? }.empty?
@project = Project.new(params[:project])
respond_to do |format|
format.html # search.html.erb
format.json { render :json => @project }
end
end
検索ビューの一部を追加する
<%= 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 のプロジェクトで行う必要があります。