加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – lambda范围内的Rails模型块错误

发布时间:2020-12-17 02:07:05 所属栏目:百科 来源:网络整理
导读:我想在我的一个模型范围内返回自定义集合. 但我不知道为什么当我在lambda范围内使用do end block时它会显示错误. 我使用rails 4.1.0和 ruby 2.1.2 .. 这是我的模型中的范围代码: scope :date,- (from_date,to_date) do buff_matches = where match_start_ti
我想在我的一个模型范围内返回自定义集合.
但我不知道为什么当我在lambda范围内使用do end block时它会显示错误.
我使用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:语法错误,意外的keyword_do_block,期望keyword_end.

但是,如果我将我的代码更改为:

scope :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语法,因为它看起来比使用花括号更清晰.你知道为什么会发生这个错误吗?

解决方法

看起来你遇到了一个边缘案例.我无法解释为什么它会失败,但这会修复它并使用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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读