【问题标题】:ActiveRecord Concern spec fails when uses self.class使用 self.class 时 ActiveRecord 关注规范失败
【发布时间】:2014-09-04 21:01:12
【问题描述】:

我有下一个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

【问题讨论】:

  • 您包含模块,这意味着这些方法可用于对象实例。您是否尝试扩展模块而不是包含它。然后它将模块中的方法添加为类方法。
  • 算了,我现在试试。
  • 它不起作用。这实际上是正确的方法,当关注extend ActiveSupport::Concern 和模型include 关注。

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


【解决方案1】:

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

您应该只使用by_site(可能首先取消范围,具体取决于您的需要)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-21
    • 1970-01-01
    • 2015-02-16
    • 1970-01-01
    • 1970-01-01
    • 2011-09-28
    • 2017-12-10
    相关资源
    最近更新 更多