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

这有助于保持数据库和数据的完整性。 –

相关问题