我在应用程序上工作,并尝试为我的用户索引实现过滤器。我在网上尝试了很多解决方案,但没有成功。我需要使用mother_tongue,locality和可用性(使用日历)进行过滤。
我首先尝试使用a simple search form solution,但我认为这不是最好的解决方案,所以我尝试使用Justin Weiss solution但它不起作用,所以我尝试将自己的过滤器放在我的用户模型中但它没有成功:
模特:
include Filterable
def self.apply_filters(params)
user = self
user = user_by_mother_tongue(mother_tongue: params[:mother_tongue]) if params[:mother_tongue].present?
user = user_by_locality(locality: params[:locality]) if params[:locality].present?
user
end
被封锁,所以我决定在过滤器上调整mother_tongue和locality并保留过滤日历以供日后使用,但是我找不到出路......
我的用户控制器:
之前:
def index
@users = User.where(activated: true).paginate(page: params[:page])
end
之后:
def index
@users = User.filter(params.slice(:mother_tongue, :locality))
end
index.html.erb:
<% provide(:title, 'Liste des utilisateurs') %>
<h1>Liste des utilisateurs :</h1>
<%= form_tag(users_path, method: :get) do %>
<%= label_tag :mother_tongue, "Langue :" %>
<%= text_field_tag :mother_tongue, params[:mother_tongue] %>
<%= label_tag :locality, "Ville :" %>
<%= text_field_tag :locality, params[:locality] %>
<%= submit_tag 'Search', name: nil %>
<% end %>
<table>
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<% for user in @users %>
<div class='user'>
<strong> <%= user.fname %> </strong>
</div>
<%= link_to 'Savoir plus', user_path(user) %>
<% end %>
</tr>
</tbody>
models / concern / filterable.rb:
module Filterable
extend ActiveSupport::Concern
module ClassMethods
def filter(filtering_params)
results = self.where(nil)
filtering_params.each do |key, value|
results = results.public_send(key, value) if value.present?
end
results
end
end
end
提前感谢您的帮助!
UsersController:
class UsersController < ApplicationController
before_action :logged_in_user, only: [:edit, :update, :destroy]
before_action :correct_user, only: [:edit, :update]
before_action :admin_user, only: [:index, :destroy]
def first; end
def second; end
def third; end
...
def index
@users = User.filter(params.slice(:mother_tongue, :locality))
end
...
private
def user_params
params.require(:user).permit(:fname, :lname, :email, :password,
:password_confirmation, :photo, :birthdate, :mother_tongue, :coach, :phone, :street_number, :locality, :route, :administrativearea_level_1, :country, :postal_code, spoken_language_ids:[])
end
...
end