2015-01-09 114 views
0

我的student_status標識存儲不同的關聯。例如,student_status_id爲1意味着學生處於活動狀態,所以我生成這些不同的id是不可或缺的。我試過創建一個沒有student_status_id 1的FactoryGirl用戶,代碼打破了告訴我沒有status_id。此外,如何使用FactoryGirl來生成說7的status_id?Ruby on Rails FactoryGirl不生成具有多個關聯的工廠

FactoryGirl.define do 
    factory :user do 
    first_name 'example' 
    last_name 'user' 
    email '[email protected]' 
    username 'example' 
    password 'abcdef' 
    password_confirmation 'abcdef' 
    birthdate DateTime.new(1990,9,1,17) 
    student 
    end 
end 

FactoryGirl.define do 
    factory :student_status do 
    name 'Active' 
    student 
    end 
end  

FactoryGirl.define do 
    factory :student do 
    points 20 
    session_minutes 120 
    weekly_session_minutes 120 
    can_schedule_self false 
    next_monthly_cycle DateTime.new(2015,9,1,17) 
    student_status_id 1 
    end 
end 

這裏的表在我的架構中定義

create_table "student_statuses", force: :cascade do |t| 
    t.string "name" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    end 

    create_table "students", force: :cascade do |t| 
    t.integer "user_id" 
    t.integer "lesson_id" 
    t.integer "points" 
    t.integer "student_status_id" 
    t.date  "next_monthly_cycle" 
    t.integer "session_minutes",  default: 0, null: false 
    t.date  "next_session_minutes" 
    t.date  "next_session_schedule" 
    t.integer "weekly_session_minutes", default: 0, null: false 
    t.boolean "can_schedule_self",  default: true, null: false 
    end 

回答

0

所以,你有一個1:1的關聯,例如student_idstudent_status表中,而student_status_idstudents表中同時出現?

試試這個:

FactoryGirl.define do 
    factory(:student) do 
    points 20 
    session_minutes 120 
    weekly_session_minutes 120 
    can_schedule_self false 
    next_monthly_cycle DateTime.new(2015,9,1,17) 
    association(:status, factory: :student_status) 
    end 
end 

FactoryGirl.define do 
    factory(:student_status) do 
    name { ['Active', 'Inactive', 'SomeOther'].sample } 
    end 
end 

此外,請確保您在Student類有這樣的:

belongs_to :student_status 

之後,從鐵軌控制檯試試這個:

FactoryGirl.load 
student = FactoryGirl.create(:student) 
puts student.status # => should return actual random status 
+0

噢,抱歉因爲那裏的混亂,學生屬於'student_status',這是否會產生這種關聯? – 2015-01-09 23:46:42

+0

@KevinBehan你可以用你確切的模式更新你的問題嗎?具體爲student/student_statuses表。從查看您提供的工廠之後詢問,您有1:1關聯。 – gmile 2015-01-09 23:51:56

+0

我仍然收到同樣的錯誤。當學生控制器中使用創建動作時,我會調用一個方法,這取決於student_status_id。它檢查一個學生是否註冊,'student_status.enrolled?',並且測試控制檯告訴我'NoMethodError:undefined method'註冊了嗎?' for nil:NilClass' – 2015-01-09 23:59:13