5
1

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 3 years have passed since last update.

form_with scope

Posted at

railsではデフォルトとして、form_with model:@userとした場合、Userモデルnew=>createと推察して勝手にレールを準備してくれる。

<%= form_with model: モデルクラスのインスタンス do |f| %>

<% end %>

例えば、以下のように記述したとき、railsは「ふむふむ、@userということはUsermodelのnewを経由して、createに飛ばせばいいんだな」と判断してくれる。

<%= form_with model:@user do |f| %>
      <%= f.label :email %>
      <%= f.email_field :email, class: 'form-control' %>

      <%= f.submit "submit", class: "btn btn-primary" %>
<% end %>

ただし、modelが存在しない場合はurlとscopeを指定してあげる必要がある。

<%= form_with url: "パス" scope: :params do |f| %>

<% end %>

<%= form_with(url: login_path, scope: :session, local: true) do |f| %>
      <%= f.label :email %>
      <%= f.email_field :email, class: 'form-control' %>

      <%= f.label :password %>
      <%= f.password_field :password, class: 'form-control' %>

      <%= f.submit "Log in", class: "btn btn-primary" %>
<% end %>
5
1
2

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
5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?