在尝试解决一个几乎不相关的问题时,我遇到了这个 Rails ActiveRecord 测试文件中的一些代码: http://github.com/rails/rails/blob/master/activerecord/test/models/post.rb
belongs_to :author_with_posts, -> { includes(:posts) }, :class_name => "Author", :foreign_key => :author_id
我明白(或者我明白吗?)->“箭头”创建了一个文字 lambda,但我不知道这是如何或为什么这是 belongs_to 的一组有效参数(名称,选项 = {})。我会期待这样的事情:
belongs_to :author_with_posts, <something that results in a key/value pair>, :class_name => "Author", :foreign_key => :author_id
上述文件充满了这种构造的实例,而且它显然工作正常,但我不知道为什么。我尝试在我自己的(显然)类似的 ActiveRecord 关联中使用 -> 语法,但它没有用,我得到了这个:
ArgumentError: wrong number of arguments(3 for 2)
似乎我缺少一些非常基本的东西?或许 post.rb 代码中包含的内容远不止这些?
最佳答案
实际上最新版本的belongs_to
需要3个参数。
第二个参数是scope
参数,在4.0.0版本中已经引入。
The Code for 4.0.0 is here ,添加scope
参数的commit为there
它对您不起作用,因为您很可能使用 rails 3.2.12。
关于ruby-on-rails - 在 Rails ActiveRecord 测试套件中使用 Ruby 1.9 lambda 文字感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15417123/