【问题标题】:Rails model block inside lambda scope errorlambda范围内的Rails模型块错误
【发布时间】:2014-08-31 11:11:05
【问题描述】:

我想在我的模型范围之一上返回自定义集合.. 但是我不知道为什么当我在我的 lambda 范围内使用 do end 块时它会显示错误.. 我正在使用 rails 4.1.0 和 ruby​​ 2.1.2 ..

这是我的模型中的作用域代码:

scope :date, -> (from_date, to_date) do
  buff_matches = where match_start_time: from_date..to_date
  matches = {}
  buff_matches.each do |match|
    buff_date = match.match_start_time.to_date.to_s
    matches[buff_date] ||= []
    matches[buff_date] << match
  end
  matches
end

它将在这一行显示错误:buff_matches.each do |match| 带有错误消息:SyntaxError: match.rb:15: syntax error, unexpected keyword_do_block, expecting keyword_end。

但是如果我把我的代码改成这样:

scope :date, -> (from_date, to_date) do
  buff_matches = where match_start_time: from_date..to_date
  matches = {}
  buff_matches.each { |match|
    buff_date = match.match_start_time.to_date.to_s
    matches[buff_date] ||= []
    matches[buff_date] << match
  }
  matches
end

它会正常工作。我想使用 do end 语法,因为它看起来比使用花括号更干净。你知道为什么会发生这个错误吗?

【问题讨论】:

标签: ruby-on-rails ruby


【解决方案1】:

您似乎遇到了极端情况。我无法真正解释为什么它会失败,但这可以修复它并使用 do..end 块

scope :date, lambda do |from_date, to_date|
  buff_matches = where match_start_time: from_date..to_date
  matches = {}
  buff_matches.each do |match|
    buff_date = match.match_start_time.to_date.to_s
    matches[buff_date] ||= []
    matches[buff_date] << match
  end
  matches
end

【讨论】:

  • 不幸的是,当我使用此代码时,我会遇到另一个错误。错误消息是:ArgumentError:试图创建没有块的 Proc 对象。我可以通过将 lambda 包裹在大括号内来抑制错误,就像这里的解决方案一样:stackoverflow.com/questions/16016668/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-17
相关资源
最近更新 更多