我从 Rails 和 RSpec 开始,但在使用 FactoryGirl 时遇到了麻烦。基本上该对象不接收属性。
模型/用户.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
规范/工厂.rb
FactoryGirl.define do
factory :user do
name "John Doe"
email "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="543e3b3c3a14312c35392438317a3b2633" rel="noreferrer noopener nofollow">[email protected]</a>"
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 '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4c262324220c29342d213c202962233e2b" rel="noreferrer noopener nofollow">[email protected]</a>' 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)
有人知道出了什么问题吗?
最佳答案
我认为你可能的意思是把 attr_accessible 而不是 attr_accessor
attr_accessible 是一个 Rails 函数,用于将字段列入白名单以进行批量分配。 attr_accessor 是一个 ruby 函数,用于生成会干扰事物的 getter 和 setter。
关于ruby-on-rails - FactoryGirl 传递 'nil' 而不是值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10065016/