ruby on rails - Drop down filter to sort products by category on index page -
i new rails , building online store. have products model , categories model association: products belong_to category , category has_many products. shoppers have ability select category in drop down , products on index page display items in category.
i able drop down show of categories using form_tag when select on category index page not filter show category.
products index.html.erb:
<%= form_tag('products', :remote => true) %> <%= select_tag "category", options_from_collection_for_select(category.all, "id", "name"), { :include_blank => true , :class => "product_select"} %> <%= submit_tag 'filter' %> <% end %>
products controller:
def index if product.all.collect == (params[:category]) @products= product.send(params[:category]) else @products = product.order(:title) end respond_to |format| format.html # index.html.erb format.js # index.js.erb format.json { render json: @products } end end
application.js:
$(document).ready -> $(".product_select").on "change", -> $.ajax url: "/products" type: "get" datatype: "script" data: dept_type: $(".product_select").val()
thanks in advance help, let me know if more information needed.
i not sure if can call db view that(i don't think so). if can shouldn't.
change category.all
here
<%= select_tag "category", options_from_collection_for_select(category.all, "id", "name"), { :include_blank => true , :class => "product_select"} %>
to @categories , set in controller.
what value of
$(".product_select").val()
also may want many many relationship products , categories. happens when want 1 product in 2 different categories?
Comments
Post a Comment