4
2

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.

find_or_initialize_byの使い方

Posted at

#find_or_initialize_byって?
モデルから渡したパラメーターに該当するものを探してくれるんだけど、あればそれを返すし、なかったらnewしてインスタンスを作ってくれるみたい!

似たようなメソッドでfind_or_create_byというcreateしてくれるものもあるらしい。

profile.update_attributes(profile_params)でバリデーションにひっかからなかったら(createorupdateしてくれる!)

reviews_controller.rb


  def create_profile
    session[:review_area_key] = params[:review_area_key]
    session[:review_provider_id] = params[:review_provider_id]
    session[:review_plan_id] = params[:review_plan_id]

    profile_params = params.permit(:nickname, :gender, :icon, :icon_color, :age, :prefecture,
                                   :provider_id, :plan_id, :month, :price, :from, :is_hikkoshi)
    session[:profile_params] = profile_params
    profile = UserProfile.find_or_initialize_by(user_id: current_user.id) ⭐️ここ
    if profile.update_attributes(profile_params)
      if (alerts = alerts_if_no_review_plan(params)).blank?
        redirect_to reviews_new2_path
      else
        redirect_to reviews_new_path(f: params[:from]), alert: alerts
      end
    else
      redirect_to reviews_new_path(f: params[:from]), alert: profile.errors.full_messages
    end
  end

いい記事 !https://qiita.com/taimuzu/items/0a21738d018f475d63ae

4
2
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
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?