型号:在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