0
0

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.

モデルオブジェクトをDBに保存する save

Posted at

モデルオブジェクトをDBに保存する save

save 行う falseを返す
save! 行う 例外ActiveRecord::RecordInvalidが発生
save(:validate => false) 行わない falseを返す
save(:validate => false) 行わない 何かシステム上の例外が発生


DBに保存できたかどううかによって処理を分岐させる

if @entry.saveredirect_to entries_path
else
render :acton => "new"
end

トランザクションの中で複数の項目を保存する

begin
Entry.transaction do
@many_entries.each {|entry| entry.save}
end
redirect_to entries_path
resucue ActiveRecord::RecordInValid,ActiveRecord::RecordNOtSaved
render :action => "input_multi_entries"
end

モデルオブジェクトを生成し、すぐにDBに保存する

# 新しいEntryを生成する
entry = Entry.new(:content => "新しい記事の本文", :blog_id => 1)
entry.new_record? #=> true
# 新しいEntryを生成し、すぐに保存する
entry = Entry.create(:content => "新しい記事の本文", :blog_id => 1)
entry.new_record? #=> false
# 新しいEntryを生成し、すぐに保存する。保存失敗時には例外を発生させる
entry = Entry.create!(:blog_id => 1)
# => ActiveRecord::RecordInvalid
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?