8
4

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 1 year has passed since last update.

app/views/blogs/new.html.erb

<%= form_with(model: @blog, local: true) do |form| %>
  <div class="blog_title">
    <%= form.label :title %>
    <%= form.text_field :title %>
  </div>
  <div class="blog_title">
    <%= form.label :content %>
    <%= form.text_field :content %>
  </div>
  <%= form.submit %>
<% end %>

app/controllers/blogs_controller.rb

class BlogsController < ApplicationController
  def index
  end

  def new
    @blog = Blog.new
  end

  def create
    Blog.create(title: params[:blog][:title], content: params[:blog][:content])
    # 追記する
    redirect_to "/blogs/new"
  end
end

app/views/blogs/new.html.erbファイルはビューファイルです。
create blog ボタンを最後に押すと、自動的にcreateアクションに行きます。
これはなぜだろうと思いました。
form_with(model:(Blog.newで作ったインスタンス変数が入っている)、インスタンス変数が空の場合。newアクションの後、createアクションに行くようになっているとのことです。

参考情報

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?