0

型號:在Rails模型中,如果未定義,belongs_to會導致回滾?

class UserPosition < ApplicationRecord 
    belongs_to :user 
    belongs_to :job_title 
end 

UserPosition的模式:

t.integer :user_id 
    t.integer :company_id 
    t.integer :industry_id 
    t.integer :department_id 
    t.integer :job_title_id 
    t.string :job_title_custom 

user_positions_controller.rb

def create 
    @user_position = UserPosition.find_or_create_by(user_id: current_user.id) 
    @user_position.update_attributes({ 
     :industry_id => params[:industry_id], 
     :department_id => params[:department_id], 
     :job_title_id => params[:job_title_id], 
     :job_title_custom => params[:job_title_custom] 
    }) 

我需要UserPosition要麼創造紀錄的智慧H:

user_id 
job_title_custom 

OR

t.integer :user_id 
t.integer :company_id 
t.integer :industry_id 
t.integer :department_id 
t.integer :job_title_id 

目前,如果我試圖創建一個UserPosition只是user_id & job_title_custom

它不工作,日誌顯示ROLLBACK的錯誤信息是:

@messages={:job_title=>["must exist"]} 

我在這裏做錯了什麼?我認爲這可能是因爲job_title在模型中定義了一種關係,但Rails指南指出它們是可選的,所以我不確定。幫助讚賞

+0

我要補充,我有一個JOBTITLE模型,job_title_custom是用戶手動輸入他們想要的任何字符串。 – AnApprentice

+0

你對UserPosition有任何驗證嗎?如果是這樣,並且驗證失敗,那麼'find_or_create_by'將會回滾。我從你的代碼中假設,用戶只能有一個user_position,對吧? – SteveTurczyn

+0

這是一個Rails 5應用程序嗎? job_title表中的關聯是否屬於belongs_to關聯? – hashrocket

回答

2

原來這是一個新的Rails 5行爲。

「在Rails 5,每當我們定義了一個belongs_to的關聯,所以需要具有存在的這種變化後默認的相關記錄。

它觸發驗證錯誤,如果相關記錄不存在。」

「In Rails 4.x world要在belongs_to關聯上添加驗證,我們需要添加必需的選項:true。」

「在Rails 5中選擇使用此默認行爲。我們可以將optional:true傳遞給belongs_to關聯,它將移除此驗證檢查。」

完整的答案:http://blog.bigbinary.com/2016/02/15/rails-5-makes-belong-to-association-required-by-default.html

+1

這有助於保持數據庫和數據的完整性。 –

相關問題