【问题标题】:Send two parameters to the same scope将两个参数发送到同一个作用域
【发布时间】:2018-02-08 16:52:26
【问题描述】:

我有个小疑问,一个作用域可以接收多个参数吗?我正在尝试这样的事情,但它标志着我的错误:

我在控制器中这样称呼它:

@search_productos_out = Producto.without_grupo(params[:id],params[:IdEmpresa])

这是范围:

scope :without_grupo, -> (id_grupo, id_empresa) {Producto.includes(:relprogrupos).references(:relprogrupos).where("relprogrupos.id IS NULL OR productos.Clave not in (select distinct ProductoId from relprogrupos where IdGrupo = ?) AND relprogrupos.IdEmpresa != ?", id_grupo, id_empresa)}

错误: 参数数量错误(给定 1,预期 2)

【问题讨论】:

  • 您的错误是“(给定 1,预期 2)”,而不是“(给定 2,预期 1)”......您还在某处使用旧方式吗?
  • 顺便说一句,这并不是当前编写的真正作用域,它只是一个滥用scope 的普通旧类方法。

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


【解决方案1】:
scope :without_grupo, lambda {|id_grupo, id_empresa| where("relprogrupos.id IS NULL OR productos.Clave not in (select distinct ProductoId from relprogrupos where IdGrupo = ?) AND relprogrupos.IdEmpresa != ?", id_grupo, id_empresa)}

这样称呼它:

Producto.includes(:relprogrupos).references(:relprogrupos).without_grupo(id_grupo, id_empresa)

它应该可以工作。

【讨论】:

    【解决方案2】:

    您也可以将其作为类方法来执行。它仍然是可链接的,并且像范围方式一样使用。

    def self.without_grupo(id_grupo, id_empresa)
      Producto.includes(:relprogrupos)
              .references(:relprogrupos)
              .where("relprogrupos.id IS NULL OR productos.Clave not in (select distinct ProductoId from relprogrupos where IdGrupo = ?) AND relprogrupos.IdEmpresa != ?", id_grupo, id_empresa)
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-23
      相关资源
      最近更新 更多