Rails ActiveRecord 麻烦
请帮助进行 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 ==)
我尝试在控制台中创建帐户,每次我将任何整数值指定为“类型”时,我都会得到“nil”。未赋值。我做错了什么?
Please help with ActiveRecord testing. Trying my first Rails 3.1.0 project. There I have model named "Account", described like:
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
And if i'm making in Rspec :
account = Account.new(:type => 1)
account.type.should == 1
I've got test result:
Failure/Error: account.type.should == 1
expected: 1
got: nil (using ==)
I tried Account creation in console, and every time i'm assigning any integer value as 'type', i got 'nil'. Not assigned value. What I'm making wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
'type' 是 Rails 中的受保护属性,因为 .type 是 ruby 方法。因此你不能批量分配它。重命名属性(例如:account_type)&一切都应该工作正常。
'type' is a protected attribute in rails, because .type is a ruby method. Hence you can't mass assign it. Rename the attribute (eg :account_type) & everything should work fine.