晚安。我的第一个 Rails 应用程序有一些问题。我有两个模型用户和个人资料。它有关联 has_one 和 belongs_to
用户.rb
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
attr_accessible :email, :password, :password_confirmation, :remember_me,:username
validates :username, presence: true
has_one :profile, dependent: :destroy
end
简介.rb
class Profile < ActiveRecord::Base
attr_accessible :aboutme, :city, :gamelevel, :phone
belongs_to :user
validates :user_id, presence: true
validates :phone, length: { in: 3..12 }
validates :phone, numericality: { only_integer: true }
end
有我的工厂:
工厂.rb
FactoryGirl.define do
factory :user do
username "Valik Leontiev"
email "Leontiev@example.com"
password "foobaryea"
password_confirmation "foobaryea"
end
factory :profile do
city "Vladikavkaz"
gamelevel "M1"
phone "8029383744"
aboutme "Hello, my friend!"
user #association with user
end
end
我已经用 rspec 测试了我的模型:
user_spec.rb 需要'spec_helper'
描述用户做
before do
@user = User.new(username: "Example User", email: "user@example.com",
password: "foobaryea", password_confirmation: "foobaryea")
end
subject { @user }
describe "profiles associations" do
before { @user.save }
let(:profile) do
FactoryGirl.create(:profile, user: @user)
end
it "should destroy associated profile" do
@profile = @user.profile
@user.destroy
@profile.should_not be_empty
Profile.find_by_id(profile.id).should be_nil
end
it "should have not more then one profile" do
Profile.where(user_id: @user.id).count > 2
should_not be true
end
end
end
我在“应该销毁关联的配置文件”块中遇到了一次失败:NoMethodError: undefined method `empty?'。那么,我是如何理解的,@user.profile 为零,为什么关联没有建立?我已经在配置文件工厂中为关联添加了“用户”。请帮帮我