以下是型号:
class User < ActiveRecord::Base
has_many :companies_users
has_many :companies, :through => :companies_users
end
class Company < ActiveRecord::Base
has_many :companies_users
has_many :users, :through => :companies_users
accepts_nested_attributes_for :users
attr_accessible :name, :address_1, :address_2, :area, :city, :state, :zipcode, :country, :users_attributes
after_create :create_subscriptions
def create_subscriptions
subscription=Subscription.create(:company_id => self.id, :subscription_dt => Date.today, :is_active => 'Y', :user_id => self.users.first.id)
subscription.save
end
end
class CompaniesUser < ActiveRecord::Base
belongs_to :user
belongs_to :company
end
以下是spec/factories/factory.rb
FactoryGirl.define do
factory :company do |f|
f.name "TestCompany"
f.domain_url "test_url"
users {|t| [t.association(:user)] }
end
factory :user do |f|
f.first_name "John"
f.last_name "Doe"
f.password "password"
f.email "JohnDoe@test.com"
f.mobile_no "25589875"
f.fax_no "25548789"
f.office_no "25578455"
end
factory :companiesuser do |f|
association :user
association :company
end
end
以下是我的规范/模型/company_spec.rb
context "Check methods" do
it "check after create methods" do
company = FactoryGirl.create(:company)
end
end
在执行上面的 company_spec 时,由于公司模型中存在方法订阅并在创建回调 create_subscriptions.which 需要 self.users.first.id 后调用,它会产生一个问题,它没有得到它并为我提供以下错误。
$ rspec spec/models/company_spec.rb
F
Failures:
1) Company Model: Check methods check after create methods
Failure/Error: company = FactoryGirl.create(:company)
RuntimeError:
Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
# ./app/models/company.rb:47:in `create_subscriptions'
# ./spec/models/company_spec.rb:45:in `block (3 levels) in <top (required)>'
谁能让我知道我需要做什么或任何与协会相关的问题?它会产生问题,因为它首先在公司中输入值,但无法在用户表中输入值,因此无法获取订阅方法中所需的用户 ID。