I have 4 checkboxes using the same scope. It's used for filtering the house with certain number of bedrooms. The last checkbox stand for "4 and more" bedroom
<%= f.check_box(:with_bedroom_num_check, {multiple: true}, '1', nil) %>
<%= f.check_box(:with_bedroom_num_check, {multiple: true}, '2', nil) %>
<%= f.check_box(:with_bedroom_num_check, {multiple: true}, '3', nil) %>
<%= f.check_box(:with_bedroom_num_check, {multiple: true}, 'more', nil) %>
When I check/uncheck these checkboxes, the parameter array passed to the scope change.
For example
xooo
When the first box is checked, the array is [1]. It should show houses with 1 bedroom.
xxxx
The array is [1, 2, 3, more]. It should show all houses.
xxoo
The array is [1, 2]. It should show houses with 1 or 2 bedrooms.
xoox
The array is [1, more]. It should show houses with 1, 4 or more bedrooms.
Currently, my scope is:
scope :with_bedroom_num_check, lambda { |flag|
where(bedroom:[flag])
}
It only works with 1-3 bedrooms. How could I show all houses with 4 or more bedrooms when the last checkbox is checked?
Try below in your scope. Before that use '4' instead of 'more' as the value of your last checkbox.
([1, 2, 3, 4] - flag).inject(all) do |x, y|
if y == 4
x.where.not("with_bedroom_num_check >= ?", y)
else
x.where.not(with_bedroom_num_check: y)
end
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.