2012-04-08 72 views
2

我開始使用Rails和RSpec,並遇到FactoryGirl的麻煩。基本上,對象不會收到屬性。FactoryGirl傳遞'nil'而不是值

模型/ user.rb

class User < ActiveRecord::Base 

    attr_accessor :name, :email, :show_name, :company, :identity, :password, :phone, :mobile 
    validates_presence_of :name, :show_name, :email, :company, :identity, :password, :phone 
    validates_uniqueness_of :email 

end 

規格/ factories.rb

FactoryGirl.define do 
    factory :user do 
     name "John Doe" 
     email "[email protected]" 
     show_name "John Doe" 
     company "Company" 
     identity "123.456.789-10" 
     password "abc123" 
     phone "1234-5678" 
     mobile "1234-5678" 
    end 
end 

Rails的控制檯

irb(main):001:0> u = FactoryGirl.create(:user) 
    (0.1ms) BEGIN 
    User Exists (0.3ms) SELECT 1 FROM `users` WHERE `users`.`email` = BINARY '[email protected]' LIMIT 1 
    SQL (0.4ms) INSERT INTO `users` (`company`, `email`, `identity`, `mobile`, `name`, `password`, `phone`, `show_name`) VALUES (NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL) 
Mysql2::Error: Column 'company' cannot be null: INSERT INTO `users` (`company`, `email`, `identity`, `mobile`, `name`, `password`, `phone`, `show_name`) VALUES (NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL) 
    (0.1ms) ROLLBACK 
ActiveRecord::StatementInvalid: Mysql2::Error: Column 'company' cannot be null: INSERT INTO `users` (`company`, `email`, `identity`, `mobile`, `name`, `password`, `phone`, `show_name`) VALUES (NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL) 

有人知道什麼是錯的?

回答

1

請勿將attr_accessor用於保存在數據庫中的屬性。 Active Record爲您生成這些訪問器。通過使用attr_accessor,您將覆蓋那些不存儲Active Record期望的值的訪問器。

2

我想你也許意味着把attr_accessible不attr_accessor

attr_accessible是Rails的功能添加到白名單字段的質量分配。 attr_accessor是一個ruby函數,用於生成干擾事物的getter和setter。

相關問題