はじめに
Railsのdevisと言うgem非常に便利ですよね。
中でもcurrent_userと言うメソッドは非常に使い勝手が良くて重宝しています。
ですが、current_userと言うメソッド。
使いどころをちゃんと理解しておらず非効率に使っていました。
と言うことで、どう非効率だったか、振り返ります。
前提
ユーザ登録ではなく、ユーザ編集の時の話です。
また、current_user以外に対して操作したい場合は、この限りではありません。
before
こんな感じで書いていました。
current_userを使って、わざわざインスタンスオブジェクトを作り出していた訳です。
registration_controller.rb
def edit_profile
@user = User.find(current_user.id)
end
def update_profile
@user = User.find(current_user.id)
@user.update(user_params)
redirect_to :next_action
end
edit.html.haml
= form_with model:@user, url:users_edit_profile_path, method: :post,local: true do |f|
= f.text_field :lastname, placeholder:'例) XX', value:"#{@user.lastname}"
= f.text_field :firstname, placeholder:'例)XX', value:"#{@user.firstname}"
= f.submit '変更する'
After
わざわざ@userを噛ませる必要なんてなかったと言う事実。
@userもcurrent_userもUserモデルに対するインスタンス変数ですよね。。
registration_controller.rb
def edit_profile
end
def update_profile
current_user.update(user_params)
redirect_to :next_action
end
edit.html.haml
= form_with model:current_user, url:users_edit_profile_path, method: :post,local: true do |f|
= f.text_field :lastname, placeholder:'例) XX'
= f.text_field :firstname, placeholder:'例)XX'
= f.submit '変更する'
そもそも、プレーンなコントローラアクションを使っていればmodel指定さえすっ飛ばせるような?
まとめ
こうやって書いていると理解していないことが多過ぎて、これをアップすることも憚られますが・・・
ただ、アウトプットしていかないと知らない、と言うことさえ知らずに過ごしてしまいそうなので頑張ります。