0

モデル:Railsモデルでは、定義されていない場合、ロールバックを引き起こしますか?

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

でUserPositionを作成しようとするとそれは動作しません

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 

現在、ログはROLLBACKを表示するエラーメッセージは次のとおりです。

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

私はここで間違って何をしていますか? job_titleにはモデル内で定義された関係があるが、Railsガイドにはオプションであることが記載されているため、それが原因であると思われるので、わからない。ヘルプは高く評価しました

+0

は、job_title_customです。 – AnApprentice

+0

UserPositionの検証はありますか?もしそうなら、検証に失敗した場合、 'find_or_create_by'がロールバックします。そして私はあなたのコードから、ユーザーはuser_positionを1つだけ持つことができると仮定します。 – SteveTurczyn

+0

これはRails 5アプリですか? job_titleテーブルのアソシエーションはbelongs_toアソシエーションですか? – hashrocket

答えて

2

これは新しいRails 5の動作です。 「我々はbelongs_toの関連付けを定義するたびに、この変更後にデフォルトで関連付けられたレコードの存在が要求されるレール5、で。

関連するレコードが存在しない場合には、検証エラーをトリガーします。」

"In Rails 4.x world belongs_to関連付けで検証を追加するには、required:trueを追加する必要があります。

"Rails 5でこのデフォルト動作をオプトアウトすることができます。この検証チェックを削除するbelongs_toアソシエーションには、オプション:trueを渡すことができます。

全回答:ユーザーが手動で彼らが望む任意の文字列を入力するために、私は私がJobTitleモデルを持っている、追加する必要がありますhttp://blog.bigbinary.com/2016/02/15/rails-5-makes-belong-to-association-required-by-default.html

+1

これは、データベースとデータの整合性を保持する意味があります。 –

関連する問題