相关疑难解决方法(0)

Rails:named_scope,lambda和blocks

我认为以下两个是等价的:

named_scope :admin, lambda { |company_id| {:conditions => ['company_id = ?', company_id]} }

named_scope :admin, lambda do |company_id| 
  {:conditions => ['company_id = ?', company_id]}
end
Run Code Online (Sandbox Code Playgroud)

但Ruby抱怨道:

ArgumentError: tried to create Proc object without a block
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

ruby lambda ruby-on-rails

52
推荐指数
4
解决办法
2万
查看次数

lambda 范围内的 Rails 模型块错误

我想在我的模型范围之一上返回自定义集合..但我不知道为什么在我的 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
Run Code Online (Sandbox Code Playgroud)

它将在这一行显示错误:buff_matches.each do |match| 带有错误消息:SyntaxError:match.rb:15:语法错误,意外的keyword_do_block,期望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
Run Code Online (Sandbox Code Playgroud)

它会正常工作。我想使用 do …

ruby ruby-on-rails

5
推荐指数
1
解决办法
436
查看次数

标签 统计

ruby ×2

ruby-on-rails ×2

lambda ×1