搜遍,无法搜索到两个属性

问题描述 投票:0回答:1

我是一个尝试制作搜索栏的初学者,我进行了简单的属性研究,工作正常,但是当我尝试在 search_field 中添加另一个属性时,我有一个错误:“Ransack 需要产品关联明确列为可搜索.在你的

ransackable_associations
”中定义一个
Product
类方法”,但它在这里!!

在我的控制之下


    class SearchController < ApplicationController
      def index
        @q = Product.ransack(params[:q])
        @products2 = @q.result(distinct: true)
      end
    end

这里是模型

    class Product < ApplicationRecord
      belongs_to :category
      has_many :product_carts
      has_many :carts, through: :product_carts

      def self.ransackable_attributes(auth_object = nil)
        ["description", "price", "title"]
      end
      end

这里有两个经过测试的有效视图

测试过的视图,这两个用单词描述搜索就可以了

    <%= search_form_for(@q, url: search_path, method: :get, class:"d- 
   flex") do |f| %>
      <%= f.search_field :title_cont, placeholder: "recherchez dans la 
    description", class: "form-control me-2" %>
      <%= f.submit "Ok !" %>
    <% end %>
    <%= search_form_for(@q, url: search_path, method: :get, class:"d- 
   flex") do |f| %>
      <%= f.search_field :description_cont, placeholder: "recherchez dans la 
    description", class: "form-control me-2" %>
      <%= f.submit "Ok !" %>
    <% end %>

但是这个不想工作,标题和描述在同一个 sqlpostgre 产品表中,只有两列,标题是一个字符串,描述是一个文本:我已经查看了很多 stackoverflow 主题,但我找不到任何明确的方式来解决这个问题!

    <%= search_form_for(@q, url: search_path, method: :get, class:"d- 
   flex") do |f| %>
      <%= f.search_field :description_or_title_cont, placeholder: "recherchez dans la 
    description", class: "form-control me-2" %>
      <%= f.submit "Ok !" %>
    <% end %>

rails error

我用 tchat gpt 尝试了其他搜索,他告诉我在模型中尝试这个,但仍然是同样的错误

tchat gpt

在此先感谢您的帮助!

ruby-on-rails search nested-attributes ransack
1个回答
0
投票

你好@samuel bellotlecoq,抱歉,但我找不到你的方法

ransackable_associations
。我遇到了同样的问题,鉴于我只想按模型中的字段进行搜索(您的案例是 Product),我在模型中定义了以下方法:

class << self
  def ransackable_attributes(auth_object = nil)
    [ "id","name" ]
  end

  def ransackable_associations(auth_object = nil)
   []
  end

结束

如果您查看代码库 here,您可以确定需要定义该方法。

希望我的回答能帮到您

© www.soinside.com 2019 - 2024. All rights reserved.