我有一个应用程序,用户可以在其位置找到一顿饭,然后他可以按类别细化。 (餐和类别是不同的模型)。
凭借我现在拥有的东西,我可以从它的位置找到一顿饭,但是当我精炼它时,显示所有其他的饭菜......
如何在内存中保持""位置,然后按类别过滤?
meals_controller.rb
class MealsController < ApplicationController
before_action :find_meal, only: [:show, :update, :edit, :destroy]
def index
filter_by_location if params[:query].present?
meal_filter = MealsFilter.new(params)
@meals ||= meal_filter.filter
@meals_count = @meals.count
#add_markers_on_map
@categories = Category.all
end
#[other actions come here]
private
def find_meal
@meal = Meal.find(params[:id])
end
def meal_params
params.require(:meal)
.permit(:menu_name,
:price,
:portion,
:availability,
:category_id,
:location,
images: [],
ingredients_attributes: [:id, :name, :_destroy])
end
def filter_by_location
@meals = Meal.search(params[:query][:location]) if params[:query][:location].present?
end
end
应用程序/服务/ meals_filter.rb
class MealsFilter
def initialize(params)
@params = params
@meals = Meal.where('availability >= ?', Date.today )
end
def filter
#filter_by_location
filter_by_category
@meals
end
private
def filter_by_category
if @params[:categories] != nil && @params[:categories].size != 0 && !@params[:categories].include?("all")
@meals = @meals.joins(:category).where("categories.name IN (?)", @params[:categories])
end
end
# def filter_by_location
# @meals = Meal.where('location LIKE?', @params[:query][:location]) if @params[:query][:location].present?
# end
end
这是我的类别过滤器:
<section class="choice" id="normal-choice">
<form action="/meals" method="get" class= "normal-form">
<ul class="list-unstyled">
<% @categories.each do |category| %>
<li>
<label class="categories">
<input type="checkbox" name="categories[]" value="<%= category.name %>"
<%= "checked" if !params[:categories].nil? && params[:categories].include?(category.name) %>>
<span>
<%= category.name %>
</span>
</label>
</li>
<% end %>
</ul>
<input class="valid-btn" type="submit" value="Filtrer">
</form>
</section>