3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

親子関係にあるテーブルで外部キーとなるIDを自動で保管して保存する

Last updated at Posted at 2013-08-02

概要

親テーブル→子テーブルの関係にあるデータをまとめて保存して
外部キーの対応も行う

モデルとテーブル作成

rails g model hoge hoge1:string
rails g model fuga fuga1:string hoge_id:integer

hoge.rb

belongs_to :pqc_sheet_name

fuga.rb

has_one :pqc_apply

save_data_model.rb

def save_data
  hoge_arr = {'hoge1' => 'hoge'}
  fuga_arr = {'fuga1' => 'fuga'}
  hoge = Hoge.new(hoge_arr)
  hoge.fuga_arr = Fuga.new(fuga_arr)
  hoge.save!
end

結果

hoge

id hoge1
1 hoge

fuga

id fuga1 hoge_id
1 fuga 1
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?