【问题标题】:ActiveRecord model subclass NoMethodError on 'create'“创建”上的 ActiveRecord 模型子类 NoMethodError
【发布时间】:2013-05-21 17:56:40
【问题描述】:

我有一个 Rails 4 beta 应用程序(在 Ruby 2 上),我遇到了一个我无法理解的错误。

我的一些规范失败了,因为我的模型类没有“create”方法,即使我是从 ActiveRecord::Base 继承的。错误消息将我的类称为模块 (undefined method 'create' for Topic:Module),这似乎很奇怪。

spec/models/topic_spec.rb:

require "spec_helper"

describe Topic do
    it "should create a new topic given valid attributes" do
        Topic.create!({:created_by_id => 1, :title => "Test" })
    end
end

app/models/topic.rb

class Topic < ActiveRecord::Base
    include ActiveModel::ForbiddenAttributesProtection

    validates :title => :presence => ture
    validates :created_by_id => :presence => true
end

错误信息:

$ rspec spec/models/topic_spec.rb

    F

    Failures:

      1) Topic should create a new topic given valid attributes
         Failure/Error: Topic.create!({:created_by_id => 1, :title => "Test" })
         NoMethodError:
           undefined method `create' for Topic:Module
         # ./spec/models/topic_spec.rrc:15:in `block (2 levels) in <top (required)>'

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    听起来您有一个名为 Topic 的模块或命名空间,它首先被加载,因此在您的测试中,Topic 并不是指您的类。是否还有其他包含主题的文件,甚至是类 Topic::Question 或类似的文件?如果是这样,请尝试将其删除或明确说明。例如,改变:

    class Topic::Question < ActiveRecord::Base
    

    class Topic
      class Question < ActiveRecord::Base
    

    【讨论】:

    • 正确的钱。该应用程序称为“主题”。非常感谢!
    猜你喜欢
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-14
    • 1970-01-01
    • 1970-01-01
    • 2019-07-06
    • 2011-09-28
    相关资源
    最近更新 更多