【问题标题】:Rails ActiveRecord troubleRails ActiveRecord 问题
【发布时间】:2011-09-10 15:06:17
【问题描述】:

请帮助进行 ActiveRecord 测试。尝试我的第一个 Rails 3.1.0 项目。我有一个名为“Account”的模型,描述如下:

migration.rb

def self.up
    create_table :accounts do |t|
      t.string :name
      t.integer :type
      t.references :user

      t.timestamps
    end
    add_index :accounts, :user_id
end

account_model.rb

class Account < ActiveRecord::Base
  belongs_to :user

  validates_length_of :name, :within => 15..255
  validates_numericality_of :type
end

如果我在 Rspec 中制作:

account = Account.new(:type => 1)
account.type.should == 1

我有测试结果:

Failure/Error: account.type.should == 1
       expected: 1
            got: nil (using ==)

我尝试在控制台中创建帐户,每次我将任何整数值分配为“类型”时,我都会得到“无”。未赋值。我做错了什么?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord rspec


    【解决方案1】:

    'type' 是 rails 中的受保护属性,因为 .type 是 ruby​​ 方法。因此你不能批量分配它。重命名属性(例如:account_type)& 一切都应该正常。

    【讨论】:

    • 我认为您也可以通过添加到您的课程中来避免它set_inheritance_column nil 也应该撤消正常的“类型”魔法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多