【问题标题】:Search with ransack gem用洗劫宝石搜索
【发布时间】:2017-04-24 18:12:29
【问题描述】:

我在视图中显示查询的结果,该查询使用两个不同的表,对于数据搜索,我使用 ransack gem 执行搜索,但它在搜索表单中显示以下错误:

ActionView::Template::Error (undefined method `Producto_cont' for Ransack::Search<class: Stoc, base: Grouping <combinator: and>>:Ransack::Search):

“Producto”字段我是从另一个名为“productos”的表中获取的,它是查询的结果,它只显示我在查询中关联的另一个字段的错误,而不是与我从“Stoc”方法中调用的那个

这是我的方法控制器:

@search = Stoc.productos_de_un_stock(params).search(search_params)
@search.sorts = 'Stock desc' if @search.sorts.empty?
@stock = @search.result().page(params[:stock]).per(15)

这是我的查询:

  def self.productos_de_un_stock(params)
      query = select("[stock].IdStock, [stock].Stock, [productos].Clave AS Clave_producto, [productos].Producto, [productosxpzas].PzaXCja AS PzaXCja")
              .joins('inner join productos ON stock.Articulo = productos.Clave inner join productosxpzas ON productos.Clave = productosxpzas.Producto')
              .where('stock.Ruta = ? AND stock.IdEmpresa = ?', (params[:search]), (params[:search6]))

      query
    end

这是我的搜索表单:

  <%= search_form_for @search, :remote=>"true", url: busqueda_stock_path, :method => :get do |f| %>
    <div class="rwd">
      <table class="table table-striped table-bordered table-condensed table-hover rwd_auto">
        <thead>
          <tr>
            <th class="component_name_header_col"><%= sort_link @search, :Articulo, "Clave","stoc", {}, { :remote => true, :method => :get } %></th>

            <th class="action_col"><%= t("basic.action") %></th>
          </tr>
          <tr>
            <th><%= f.text_field :Articulo_cont, class:"campo" %></th>
            <%= f.search_field :Producto_cont %>
              <input id="search" type="hidden" value="<%=params[:search] %>" name="search"/> 
            <input id="search6" type="hidden" value="<%=params[:search6] %>" name="search6"/>


            <th><%= f.submit "Buscar" %></th>
          </tr>

        </thead>
        <tbody>

        </tbody>
      </table>
    </div>
  <% end %>

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 ransack


    【解决方案1】:

    首先,按照惯例,尝试将列命名为不使用大写。

    我们需要表格和模型的结构来给出更好的答案,所以请尝试将它们添加到问题中。

    但我会尽量给你一些案例,以便你解决问题

    如果您尝试使用 has_many 关系,您将首先以复数形式调用该关系,然后调用该模型的列,例如,如果用户有很多项目,我们想按项目名称搜索,它会是这样的

     <%= f.search_field :projects_name_cont %>
    

    如果用户属于机构,我们会先用单数,然后到模型的列,像这样

    <%= f.search_field :institution_name_cont %>
    

    如果我们尝试使用同一用户模型中的列,那么它将直接

     <%= f.search_field :name_cont %>
    

    它将直接转到用户模型中的名称列。希望能帮助你理解

    【讨论】:

    • 感谢您的回复,非常感谢您提供的示例,我理解您的意思,但如果我想从查询中获取数据,请选择使用“AS”重命名字段的位置?例如从这部分:: select("[rutas].Ruta AS ruta, [clientes].IdCli AS Cliente")
    猜你喜欢
    • 2012-11-08
    • 1970-01-01
    • 1970-01-01
    • 2019-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多