【发布时间】:2016-08-15 12:21:40
【问题描述】:
我对 Rails 很陌生,正在建立一个在线商店。我目前有一个产品模型和一个具有关联的类别模型:产品属于_to 一个类别和一个类别 has_many 产品。我希望购物者能够在下拉列表中选择一个类别,并且索引页面上的产品将仅显示该类别中的项目。
我能够使用 form_tag 获得一个下拉菜单来显示所有类别,但是当我在一个类别上选择时,索引页面不会过滤以仅显示该类别。
产品索引.html.erb:
<%= form_tag('products', :remote => true) do %>
<%= select_tag "category", options_from_collection_for_select(Category.all, "id", "name"), { :include_blank => true , :class => "product_select"} %>
<%= submit_tag 'Filter' %>
<% end %>
产品控制器:
def index
if Product.all.collect == (params[:category])
@products= Product.send(params[:category])
else
@products = Product.order(:title)
end
respond_to do |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()
提前感谢您的帮助,如果需要更多信息,请告诉我。
【问题讨论】:
-
我认为你的代码总是在索引上的 else 条件下运行
-
您可以在这个问题中从 OP 的代码中获得一些输入:stackoverflow.com/questions/36676443/…
标签: ruby-on-rails filter associations