繁体   English   中英

模型范围内的参数错误

[英]Argument error in model scope

我正在尝试通过将大部分查询移到一个范围company_search_params来重构Companies_Controller#index方法以包含较少的逻辑。

将参数传递到模型范围的最佳方法是什么? 我遇到了错误,参数数量错误(给定0,预期为1) 我在编写作用域方面相对较新,在传递适用于Rails指南的参数/条件方面找不到很多。

公司财务总监

 def index
    params[:name_contains] ||= ''
    Company.company_search_params(params[:name_contains])

    @search = Company.company_search_params
    @companies = @search.page(params[:page])
  end

公司模式

scope :company_search_params, ->(name_contains){
    where(
    <<-SQL
      "name LIKE :match OR subdomain LIKE :match", { match: "%#{name_contains}%" }
    SQL
    ).where(is_archived: false).order(name: :asc)
  }

谢谢你的帮助。

使用named_scope示例和信息

scope :named_scope, lambda {
  |variable1, variable2|
  where...
  order...
}

#when you call it from your controller

Model.named_scope("value 1","value 2")

为了你的问题

在您的company.rb中

scope :company_search_params, lambda { 
  |name_contains|
  where(
  <<-SQL
    "name LIKE :match OR subdomain LIKE :match", { match: "%#{name_contains}%" }
  SQL
  ).where(is_archived: false).order(name: :asc)
}

company_controller.rb

def index
  @search = Company.company_search_params(params[:name_contains])
  @companies = @search.page(params[:page])
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM