型號:在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指南指出它們是可選的,所以我不確定。幫助讚賞
我要補充,我有一個JOBTITLE模型,job_title_custom是用戶手動輸入他們想要的任何字符串。 – AnApprentice
你對UserPosition有任何驗證嗎?如果是這樣,並且驗證失敗,那麼'find_or_create_by'將會回滾。我從你的代碼中假設,用戶只能有一個user_position,對吧? – SteveTurczyn
這是一個Rails 5應用程序嗎? job_title表中的關聯是否屬於belongs_to關聯? – hashrocket