Skip to content

Instantly share code, notes, and snippets.

@libitte
Last active September 29, 2015 13:07
Show Gist options
  • Save libitte/693fd852aeff4765fea6 to your computer and use it in GitHub Desktop.
Save libitte/693fd852aeff4765fea6 to your computer and use it in GitHub Desktop.

Creates an object (or multiple objects) and saves it to the database, if validations pass. The resulting object is returned whether the object was saved successfully to the database or not.

http://api.rubyonrails.org/classes/ActiveRecord/Persistence/ClassMethods.html#method-i-create

The resulting object is returned whether the object was saved successfully to the database or not. (再掲)

これは盲点だった。

つまり、以下のように書いてしまうと間違い。

create は save の成功可否にかかわらず、一応結果オブジェクトを返してしまうので、これだと必ず succeeded_path にリダイレクトされる。 失敗している場合、MyModel にレコードは作成されていない。

if MyModel.create(myparams)
  redirect_to succeeded_path and return
else
  redirect_to failed_path and return
end

正しくは、何でもいいが例えば例外を使わないなら、下記のようにする。

my_model = MyModel.new(myparams)
if my_model.save
  redirect_to succeeded_path and return
else
  redirect_to failed_path and return
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment