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

フォームからのデータを保存できない

Posted at

データの保存

フォームからのデータを保存するために、以下のようにコードを。しかしながら、2つの誤りが原因でデータが正しく保存できませんでした。

app/views/posts/new.html.erb
<h1>新規投稿ページ</h1>
<%= form_with url: "/posts", method: :post, local: true do |form| %>
  <%= form.text_field :context %>
  <%= form.submit '投稿する' %>
<% end %>
config/routes.rb
Rails.application.routes.draw do
  get 'posts', to: 'posts#index'
  get 'posts/new', to: 'posts#new'
  post 'posts', to: 'posts#create'
end
app/controllers/posts_controller.rb
class PostsController < ApplicationController
  def index
    @posts = Post.all
  end

  def new
  end

  def create
    Post.new(content: params[:content])
  end
end

① text_fieldで指定した値がcontextになっているが、コントローラーで受け取っているパラメーターはparams[:content]であるため
② Post.newでインスタンス(レコード)を生成しただけで保存していないため
①については、問題で提示したフォームでは、params[:content]の中身は空っぽです。データをコントローラーで受け取るためには、params[:context]とするか、<%= form.text_field :content %>と修正。名前は揃えた方がわかりやすいのので、意図がなければ後者の方が望ましい。

②については、1行で書くのであればPost.create(content: params[:content])として、インスタンスの生成と保存を一度に行ってしまうことが望ましい。一方で、以下のように記述しても、データは保存できます。

```rb
def create
post = Post.new(content: params[:content])
post.save
end

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