rails 1到4升级:include关键字

时间:2015-05-26 13:27:10

标签: ruby-on-rails-4 activerecord

我有一大堆Rails 1代码在模型中使用了这种语法:

...
has_many :widgets, :class_name => 'WidgetAssertion', 
                   :include => [ :activity, :priority_assertion_type ]
...

Rails 4抛出异常:

(ArgumentError in WhateverController#index) 
(Unknown key: :include. Valid keys are: :class_name, :class, :foreign_key,
:validate, :autosave, :table_name, :before_add, :after_add, :before_remove, 
:after_remove, :extend, :primary_key, :dependent, :as, :through, :source, 
:source_type, :inverse_of, :counter_cache, :join_table, :foreign_type)

如何将其移植到Rails 4?

1 个答案:

答案 0 :(得分:2)

has_many的第二个参数是scope

  

您可以传递第二个参数scope作为可调用的(即proc或lambda)来检索特定的记录集,或者在访问关联的集合时自定义生成的查询。

因此,在您的示例中,您可以执行此操作:

has_many :widgets, -> { includes(:activity, :priority_assertion_type) },
         class_name: 'WidgetAssertion'