升级到Rails 3,has_many关联扩展不再适用于范围

时间:2010-11-26 13:10:21

标签: activerecord ruby-on-rails-3

我正在将rails 2.3应用程序升级到rails 3.0.3

我的Product模型

上有以下关联扩展和范围
 has_many :related_products, :through => :product_related_products do
    [:alternative, :complement, :bigger_pack, :higher_quantity, :lower_quality].each do |meth|
    define_method(meth) {
       find :all, :conditions => ["product_related_products.#{meth} = ?", true] }
    end
 end

scope :visible, where(:hidden => false)

概念取自:http://guides.rubyonrails.org/association_basics.html#association-extensions

当我在链中调用关联时

 @product.related_products.visible.alternative

它在rails 2.3中工作正常,我在Rails 3中得到以下错误:

 undefined method `alternative' for #<ActiveRecord::Relation:0x1047ef978>

 activerecord (3.0.3) lib/active_record/relation.rb:371:in `method_missing'
 app/views/products/show.html.haml:18:in `_app_views_products_show_html_haml___1131941434_2185376080_0'

我认为它与创建的新关系有关,但我不知道如何继续,rails指南仍然建议这种方法没问题。

//在François建议的更改后编辑:

类定义如下:

class Product < ActiveRecord::Base
  has_many :product_related_products
  has_many :related_products, :through => :product_related_products
end

class ProductRelatedProduct < ActiveRecord::Base
  belongs_to :product
  belongs_to :related_product, :class_name => "Product"

  scope :with_attribute, lambda {|attr| where(attr, true)}

end


@product.related_products.with_attribute(:alternative) raises: 

NoMethodError Exception: undefined method `with_attribute' for #<Class:0x108fbd8b8>

1 个答案:

答案 0 :(得分:0)

在相关类中定义范围:

class RelatedProduct < ActiveRecord::Base

  scope :visible, where(:hidden, false)

  %w(alternative complement bigger_pack higher_quantity lower_quality).each do |attribute|
    scope attribute, where(attribute, true)
  end

end

@product.related_products.visible.bigger_pack

或者,创建一个期望您要搜索的属性的方法:

class RelatedProduct < ActiveRecord::Base
  scope :with_attribute, lambda {|attr| where(attr, true)}
end

@product.related_products.visible.with_attribute(:bigger_pack)