Reputation: 9
I'm working on an application, I actually implement a filter on my user index to search some users by : Language, city and availability(date). The filter by language and city work perfectly but not for the date.
index.html.erb :
<div>
Date de départ :
<%= f.text_field :with_start_time_gte, 'data-provide' => 'datepicker' %>
</div>
<%= f.submit 'Rechercher' %>
I create a model Availability with params (:name, :start_time, :end_time, :user_id) User has_and_belongs_to_many :availability and availability belongs_to :user. I need that the filter search between the date between start_time and end_time of the availabilities and return the users available.
users_controller.rb :
def index
@filterrific = initialize_filterrific(
User,
params[:filterrific]
#persistence_id: 'shared_key',
#default_filter_params: {},
#available_filters: [],
) or return
@users = @filterrific.find.page(params[:page])
# Respond to html for initial page load and to js for AJAX filter updates.
respond_to do |format|
format.html
format.js
end
rescue ActiveRecord::RecordNotFound => e
# There is an issue with the persisted param_set. Reset it.
puts "Had to reset filterrific params: #{ e.message }"
redirect_to(reset_filterrific_url(format: :html)) and return
end
user.rb :
filterrific(
default_filter_params: {},
available_filters: [
:with_mother_tongue,
:with_locality,
:with_start_time_gte])
scope :with_mother_tongue, -> (search_string) {
where("users.mother_tongue LIKE ?", (search_string.to_s.gsub('*', '%') + '%').gsub(/%+/, '%'))
}
scope :with_locality, -> (search_string) {
where("users.locality LIKE ?", (search_string.to_s.gsub('*', '%') + '%').gsub(/%+/, '%'))
}
scope :with_start_time_gte, lambda { |ref_date|
where('users.availabilities.start_time >= ?', ref_date)
}
I think the problem is in the scope to take start_time from availabilities of user... But don't know how to do... Thanks in advance for your help !
Upvotes: 0
Views: 329
Reputation: 5609
First, your relationship between User
and Availability
is wrong. An HABTM relation should be shared between the two models with a join table (source)
Change to a has_many/belongs_to
relationship if Availability just belongs to one User.
For your scope you have to join the relationship in the query:
scope :with_start_time_gte, -> (ref_date) { joins(:availabilities).where('availabilities.start_time >= ?', ref_date) }
Upvotes: 1