2012-08-14 69 views
2

获取“您不能调用create,除非父母被保存”错误这使我疯狂。 FactoryGirl已停止工作,但我看不出为什么或如何 - 可能是我的宝石更新?首先这个问题,详细信息:FactoryGirl

>>> c = FactoryGirl.create(:client) 
=> #<Client id: 3, name: "name3", email: "[email protected]", password_digest: "$2a$10$iSqct/0DIQbL.OcRrYOiPuiKijbAXggLxcMevS3TmVIV...", created_at: "2012-08-14 23:25:22", updated_at: "2012-08-14 23:25:22"> 
>>> a = FactoryGirl.create(:admin) 
ActiveRecord::RecordNotSaved: You cannot call create unless the parent is saved 
     from /.../usr/lib/ruby/gems/1.9.1/gems/activerecord-3.2.1/lib/active_record/associations/collection_association.rb:425:in `create_record' 

调试打印语句告诉我,:admin是一个new_record?所以我自然不能与它的关联。这是客户工厂。这个想法是,管理员仅仅是已分配管理权限的客户端:

FactoryGirl.define do 
    factory :client do 
    sequence(:name) {|n| "name#{n}"} 
    sequence(:email) {|n| "client#{n}@example.com" } 
    password "password" 

    factory :admin do 
     after_create {|admin| 
     admin.assign_admin 
     } 
    end 

    end 

end 

当我在控制台什么FactoryGirl正在做(或应该做的)复制,一切都工作好:

>>> a = FactoryGirl.create(:client) 
=> #<Client id: 4, name: "name5", email: "[email protected]", password_digest: "$2a$10$vFsW6VfmNMKWBifPY3vcHe6Q2.vCCLEq3RqPYRxdMo0m...", created_at: "2012-08-14 23:37:11", updated_at: "2012-08-14 23:37:11"> 
>>> a.assign_admin 
=> #<ClientRole id: 2, client_id: 4, role: 1, created_at: "2012-08-14 23:37:28", updated_at: "2012-08-14 23:37:28"> 
>>> a.admin? 
=> true 

这里的客户端模式:

class Client < ActiveRecord::Base 
    attr_accessible :name, :email, :password, :password_confirmation 
    has_secure_password 
    validates_presence_of :name, :email, :password, :on => :create 
    validates :name, :email, :uniqueness => true 
    has_many :sites, :dependent => :destroy 
    has_many :client_roles, :dependent => :destroy 
    # roles 

    def has_role?(role) 
    client_roles.where(:role => role).exists? 
    end 

    def assign_role(role) 
    client_roles.create(:role => role) unless has_role?(role) 
    end 

    def revoke_role(role) 
    client_roles.where(:role => role).destroy_all 
    end 

    def assign_admin 
    assign_role(ClientRole::ADMIN) 
    end 

    def admin? 
    has_role?(ClientRole::ADMIN) 
    end 

end 

而对于完整性,该ClientRole型号:

class ClientRole < ActiveRecord::Base 
    belongs_to :client 

    # values for #role 
    ADMIN = 1 

end 

最后,版本,并从Gemfile.lock的依赖性信息:

factory_girl (4.0.0) 
    activesupport (>= 3.0.0) 
factory_girl_rails (4.0.0) 
    factory_girl (~> 4.0.0) 
    railties (>= 3.0.0) 

回答

8

解决。 FG的最新版本发生了一些变化。曾经工作过的工厂如下方法:

factory :admin do 
    after_create {|admin| 
    admin.assign_admin 
    } 
end 

,但最近的文件说,语法是现在:

factory :admin do 
    after(:create) {|admin| 
    admin.assign_admin 
    } 
end 

改变它使一切工作。 whew

+1

+1感谢您的更新。我是一个好奇的新手。 :-) – azhrei 2012-08-15 02:29:42