首页 > 解决方案 > 使用按钮按类别过滤?

问题描述

我已经为此寻找了几个小时,但没有找到似乎对我有用的解决方案,我对此也是新手。

我目前有一个有效的搜索字段。

但我想添加一个单独的功能,您可以在其中单击链接、类别,然后显示该类别中的产品。

列表控制器(产品):

def index
  @listings = Listing.all
  if params[:search]
    @listings = Listing.search(params[:search]).order(created_at: :desc)
  else
    @listings = Listing.all.order(created_at: :desc)
  end
  @categories = Category.all
end

listing.rb模型:

  belongs_to :user
  belongs_to :category, required: false
  attr_accessor :new_category_name
  before_save :create_category_from_name

  def create_category_from_name
    create_category(name: new_category_name) unless new_category_name.blank?
  end

  def self.search(search)
    where("name LIKE ?","%#{search}%")
  end

类别型号:

has_many :listings
CATEGORY = %w{ cat1 cat2 cat3 cat4 }

看法:

<% @categories.each do |cat| %>
  <%= link_to cat.name, listings_path(:category_id => @listings) %>
<% end %>

这是我的架构(列表和类别):

  create_table "categories", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "listings", force: :cascade do |t|
    t.string "name"
    t.text "description"
    t.decimal "price"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "image"
    t.integer "user_id"
    t.integer "category_id"
    t.index ["category_id"], name: "index_listings_on_category_id"
  end

我的控制器或我的观点是错误的。我假设我的控制器需要更多定义..我该怎么做?

标签: ruby-on-railsruby

解决方案


我想添加一个单独的功能,您可以在其中单击链接、类别,然后显示该类别中的产品

你这样做是不对的。您应该在路径助手中传递类别并过滤该类别的列表

#view
<%= link_to cat.name, listings_path(:category => cat) %>

#controller
def index
  if params[:search]
    @listings = Listing.search(params[:search]).order(created_at: :desc)
  #add this line
  elsif params[:category]
    @listings = Category.find(params[:category]).listings
  else
    @listings = Listing.all.order(created_at: :desc)
  end
  @categories = Category.all
end

推荐阅读