ruby-on-rails - 使用按钮按类别过滤?
问题描述
我已经为此寻找了几个小时,但没有找到似乎对我有用的解决方案,我对此也是新手。
我目前有一个有效的搜索字段。
但我想添加一个单独的功能,您可以在其中单击链接、类别,然后显示该类别中的产品。
列表控制器(产品):
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
我的控制器或我的观点是错误的。我假设我的控制器需要更多定义..我该怎么做?
解决方案
我想添加一个单独的功能,您可以在其中单击链接、类别,然后显示该类别中的产品
你这样做是不对的。您应该在路径助手中传递类别并过滤该类别的列表
#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
推荐阅读
- stata - 另一个假人之间的假人
- network-programming - GameMaker Studio 2 网络错误:Socket ConnectWrap 失败错误:-1
- c++ - 在 C++ 中使用 if 语句的最有效方法
- javascript - 如何将“div”列表保存到 sessionStorage 并在用户重新加载页面时显示它们?
- mysql - 无法使用 MAMP 访问 PhpMyAdmin
- python - 齿轮在 discord.py 加载扩展中不起作用
- .net - 带有 Angular 应用程序的 .NET Core 无法在 Visual Studio 2019 中打开
- bash - 获取包含任何 .py 文件的目录的名称
- google-sheets - 为什么连字符会搞砸我的重复查找条件格式?
- c# - 是否可以从依赖项中打开winform表单?