【问题标题】:Rails scope paramsRails 范围参数
【发布时间】:2018-06-03 05:46:33
【问题描述】:

尝试使用范围编写一个简单的搜索,但是我得到了一个奇怪的响应,我想知道是否有人可以解释我的错误。

  scope :sounds_like, -> (item) { where('title ILIKE ?', "#{ params[:sounds_like] }%")}

我的控制器看起来像

 def index
    @items = Item.sounds_like(params[:sounds_like])
 end

尝试从 API 搜索时出现以下错误。

NameError (undefined local variable or method `params' for #<Class:0x00007ff553a054d8>):

有没有什么方法可以在不使用表单传递的参数的情况下将参数传递给模型?

【问题讨论】:

  • 仔细阅读您的代码。
  • 您的作用域应该引用它的item 参数,而不是查看params(仅在控制器中可用):where('title ILIKE ?', "#{item}%")。大概您最初在控制器方法中编写了范围的查询,然后将其移至范围。

标签: ruby-on-rails scope


【解决方案1】:

Rails 模型不支持请求 - 它们无权访问参数、请求对象或会话。

要将参数从控制器传递给模型,请将它们作为方法参数传递:

class Thing < ApplicationRecord

  def self.sounds_like(value)
    where('title ILIKE ?', "#{ value }%")
  end
end

# call it as:
Thing.sounds_like('foo')

scope is just a syntactic sugar 可以让你简洁地编写类方法。所以上面会写成:

class Thing < ApplicationRecord
  scope :sounds_like, ->(value){ where('title ILIKE ?', "#{ value }%")}
end

scope 的第二个参数是 lambda - 这是一个匿名函数,其作用类似于方法:

irb(main):001:0> l = -> (v) { puts v }
=> #<Proc:0x007f81dca27d48@(irb):1 (lambda)>
irb(main):002:0> l.call("Hello World")
Hello World
=> nil

括号表示 lambda 的参数,就像定义方法时一样:

irb(main):016:0> lamb = -> (a, b) { [a,b].join(" ") }
=> #<Proc:0x007f81dc983ec8@(irb):16 (lambda)>
irb(main):017:0> lamb.call("Hello", "World")
=> "Hello World"

【讨论】:

    【解决方案2】:

    根据提供的描述,以下代码将不起作用:

    scope :sounds_like, -> (item) { where('title ILIKE ?', "#{ params[:sounds_like] }%")}
    

    因为参数在模型中不可用。

    将上述书面范围修改为以下内容:

    scope :sounds_like, -> (item) { where('title ILIKE ?', "%#{item}%") }
    

    在上述范围内,项目将是您将从控制器传递的参数。

    【讨论】:

      【解决方案3】:

      在你的范围内遵循这个

      scope :sounds_like, -> (item) { where('title ILIKE ?', "%#{item}%") }
      

      它应该可以工作。

      有关 Rails 范围的更多信息,您可以查看 article

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-10-17
        • 1970-01-01
        • 1970-01-01
        • 2019-01-16
        • 1970-01-01
        • 2018-06-24
        • 1970-01-01
        相关资源
        最近更新 更多