使用self.class时,ActiveRecord Concern规范失败

时间:2014-09-04 21:01:12

标签: ruby-on-rails ruby-on-rails-3 activerecord activesupport-concern

我有下一个Siteable问题:

module Siteable
  extend ActiveSupport::Concern

  included do
    belongs_to :site

    scope :by_site,  lambda { |site| where(site_id: site.try(:id)) }
    scope :for_site, lambda { |site| by_site self.class.by_site(site).any? ? site : nil }
  end
end

有这种担忧的示例模型:

class IndustryLink < LinkResource
  require 'concerns/siteable.rb'
  include Siteable

  belongs_to :author, :class_name => 'User'
  belongs_to :industry
  validates_presence_of :name, :link
end

它在服务器上运行良好。但是这个模型的所有规格都失败了类似的错误:

 Failure/Error: industry = Factory(:industry, :name => 'new industry')
 NoMethodError:
   undefined method `by_site' for Class:Class
 # ./app/models/concerns/siteable.rb:8:in `block (2 levels) in <module:Siteable>'
 # ./app/models/industry_link.rb:12:in `get_objects'
 # ./app/models/concerns/reorderable.rb:47:in `add_number'
 # ./spec/views/sitemap/show.xml.builder_spec.rb:41:in `block (2 levels) in <top (required)>'

所以,显然self.class在这种情况下不是Industry,我不知道如何解决这个问题。

如果我将for_site移到模型并将self.class更改为Industry规格传递。

检查ruby 1.9.3,2.1.1,Rails 3.2.19

1 个答案:

答案 0 :(得分:1)

在你的lambda中,self已经是模型类 - Industry,所以self.classClass

你应该只使用by_site(可能首先取消它,取决于你需要的东西)