如果用户选择预定义的过滤器链接,我的索引将如何根据该请求显示结果?
<h1>Products</h1>
<% @products.each do |product| %>
<%= link_to product.name, product_path(product) %>
<% end %>
<h2>Find Product by Category</h2>
Electronics
Apparel
Books
例如,如何创建“电子产品”链接来过滤产品索引,使其仅包含“电子产品”类别的产品? “类别”字段/列已在我的数据库/模型中定义。
这就是我的 Controller 目前的样子:
def index
@products = Product.all
end
谢谢。
最佳答案
使您的链接成为返回产品的链接,但添加类别作为网址参数。
然后在您的 Controller 中,如果该参数存在,则根据它过滤结果。如:
查看:
<h2> Find Product by Category </h2>
<%= link_to "Electronics", products_path(:category=>"electronics")
Controller
def index
if params[:category]
@products = Product.where(:category => params[:category])
else
@products = Product.all
end
end
基于egyamado的评论:
如果您想添加即时消息,则如下所示:
def index
if params[:category]
@products = Product.where(:category => params[:category])
flash[:notice] = "There are <b>#{@products.count}</b> in this category".html_safe
else
@products = Product.all
end
end
如果您只想在没有产品时显示消息,则只需将 if @products.empty?
添加到 Flash 名称的末尾
或者,如果您想在没有产品时显示错误消息,在有产品时显示通知,则可以将其设置为完全有条件的
def index
if params[:category]
@products = Product.where(:category => params[:category])
if @products.empty?
flash[:error] = "There are <b>#{@products.count}</b> in this category".html_safe
else
flash[:notice] = "There are <b>${@products.count}</b> in this category".html_safe
end
else
@products = Product.all
end
end
关于ruby-on-rails - Rails 使用链接(无下拉菜单)过滤索引结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19760527/