LoginSignup
6
3

More than 3 years have passed since last update.

new_record?で場合分け ❏Rails❏

Last updated at Posted at 2019-12-06

newとeditで同一の部分テンプレートを利用しているが、それぞれちょっとだけ変えたい時

Railsのnew_record?メソッドを使って場合分けすることができます。

・インスタンスが新規作成されて、情報がないものはtrue
・インスタンスに既に情報が保存されている場合はfalse

_form.html.haml
- if tweet.new_record?
  %p 新規作成
- else
  %p 編集

= form_with model: tweet, local: true do |form|
...
new.html.haml
= render "form", tweet: @tweet
edit.html.haml
= render "form", tweet: @tweet

newページでは新規作成が、
editページでは編集が表示されるようになりました。

直感的で非常にわかりやすいです。



前回 current_page?による場合分けを解説しました。

https://qiita.com/ITmanbow/items/dc9b2e2b48f4901049f4

しかしこのやり方だとURL設計の変更に弱いという弱点を指摘されました。(ありがとうございます。)
ですので、登録フォームの場合分けはnew_record?を使う方が良いと思います。



参考

https://programming-beginner-zeroichi.jp/articles/35



ではまた!

6
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
6
3