【问题标题】:Rails, How to show all product by category search feature?Rails,如何按类别搜索功能显示所有产品?
【发布时间】:2018-03-31 16:58:54
【问题描述】:

现在我想在我的项目中添加一些添加搜索功能。我有 2 个关于产品和类别的表,然后我使用一对多关系。当我想按类别搜索我的产品时,我遇到了困难。这是我的代码:

products_controller.rb:

def index
  @product = Product.all
  render json: @product, status: :ok 
end

def search    
 @category = Category.find(params[:category_id])
 @product = @category.products

 render json: @product, status: :ok
end

def show
  render json: @product, status: :ok
end

routes.rb

Rails.application.routes.draw do  
namespace :v1 do 

  resources :products
  resources :categories


  post 'products/search', to: "products#search"
  get 'products/search', to: "products#search"

  end
end

模型category.rb

class Category < ApplicationRecord
  has_many :products
end

模型product.rb

class Product < ApplicationRecord
  belongs_to :category
end

我的产品表字段

  t.integer :category_id
  t.string :product_name
  t.string :company
  t.text   :description
  t.string :logo_img
  t.string :web_link

我的表格类别字段

  t.string :category_name
  t.string :status

类别展示他们所有的产品应该如何工作? 感谢您的帮助

【问题讨论】:

  • @product = @category.products@product 定义为该类别所有产品的列表。最好命名为@products,因为它更准确。你的代码有什么特别的地方不起作用?
  • 我也会考虑使用像 solr 这样的索引服务。我知道您对 Rails 很陌生,但如果您想在 RoR 中工作,它是一个很棒的工具

标签: ruby-on-rails ruby search associations one-to-many


【解决方案1】:

添加您的 categories_controller.rb 如下 类别控制器.rb 定义显示 类别 = Category.find(params[:id]) 呈现 json:category.products,状态::ok 结尾 结束

并访问/categories/:id url

【讨论】:

  • 谢谢帮帮我,问题可以通过加入表格来解决。
猜你喜欢
  • 1970-01-01
  • 2015-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多