2016-12-05 63 views
0

我有一個使用STI從用戶模型繼承的學生模型。用戶型號has_one profile。從表單創建新學生時,學生管理員的創建操作成功生成了學生模型的實例以及學生個人資料的實例,可以通過@student.profile進行檢查。在這個階段,student.id,profile.id和profile.user_id都是零。在rails 4下,我可以執行@ student.save,並且學生和相關模型都將被保存。然而,在導軌5,@ student.save返回false,並顯示一條錯誤消息如何保存與rails的關聯5

:"profile.user"=>["can't be blank"] 

如何保存@student實例憑藉其在軌5聯想?

相關的代碼是

def create 
    @student = build_student(params[:student]) 
    if @student.save 

回答

0

我已成立

Rails.application.config.active_record.belongs_to_required_by_default=false 

,並在剖面模型,我已經建立

validates :user, presence: true 

這是老同學,所以很清楚爲什麼它不適用於rails 5。我試着在profile.rb

belongs_to user, required: true 

但這並沒有工作,給人一種錯誤

"profile.user"=>["must exist"] 

最後,我只設置

Rails.application.config.active_record.belongs_to_required_by_default=true 

和使用optional: true爲我的模型,其可以保存而不屬於用戶。