foreign keyを使う

Railsでリレーションを使いたい時のこと




【1.問題】

                                                      • -

Mysql::Error: #23000Cannot add or update a child row: a foreign key constraint fails:
INSERT INTO students (`department`, `ph 〜 

                                                      • -

というエラーになる。

原因:親より先に子を作っているから。特に、scaffoldでやると一発でこれになる。



【2.対処方法】
▼1.モデルの関連付け。belongs_to
▼2.createする前に、親を生成して子に関連付ける(!これが大切!)

def create
    @student = Student.new(params[:student])
   # ac = ApplyChannel.create(:name => "Mainavi")
   # ss = StudentStatus.create(:name => "Entry")
   # @student.apply_channel = ac
   # @student.student_status = ss
    
    if @student.save
      flash[:notice] = 'Student was successfully created.'
      redirect_to :action => 'list'
    else
      render :action => 'new'
    end
  end

ここでの、ポイントは、dbでは、
constraint fk_students_channel foreign key (apply_channel_id) references apply_channels(id),
なっているので、
ac_id = ApplyChannel.create(:name => "Mainavi").idとかにしそう。これはエラーする。



!なんとこれでいい
@student.apply_channel = ac
student.apply_channeで参照できるようになっている。基は、_idと宣言したにも関わらず。
これによって、 student.apply_channe.nameもできる!