質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Haml

Haml(HTML abstraction markup language)は、HTML/XHTMLを効率的に記述するためのマークアップ言語および記法です。

Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Q&A

解決済

1回答

1326閲覧

createアクションで保存されない

ochibi1

総合スコア1

Haml

Haml(HTML abstraction markup language)は、HTML/XHTMLを効率的に記述するためのマークアップ言語および記法です。

Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

0グッド

0クリップ

投稿2020/07/16 11:00

編集2020/07/16 16:13

#前提
ruby on rails で初歩的なブログサービスの作成中です。
articleモデルと、userモデルを紐づけて投稿機能を実装しています。
#解決したいこと
newアクションの新規投稿画面で、新規登録ボタンを押すと、「作成しました」と表示が出ていたのですが、どこかを書き間違えたのか、入力時の画面に戻ってしまうようになりました。投稿内容がデータベースに保存されるようにしたいです。
ど初歩的な質問です恐縮ですが、よろしくお願いします。
#該当のコード

schema.rb

ActiveRecord::Schema.define(version: 2020_07_15_083420) do create_table "articles", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t| t.string "title" t.text "body" t.string "img" t.bigint "user_id" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.index ["user_id"], name: "index_articles_on_user_id" end create_table "users", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t| t.string "email", default: "", null: false t.string "encrypted_password", default: "", null: false t.string "nickname" t.string "reset_password_token" t.datetime "reset_password_sent_at" t.datetime "remember_created_at" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.index ["email"], name: "index_users_on_email", unique: true t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true end end

config/routes.rb

Rails.application.routes.draw do devise_for :users, controllers: { sessions: 'users/sessions' } resources :articles root "articles#index" end

articles_controller.rb

class ArticlesController < ApplicationController before_action :authenticate_user! before_action :move_to_index, except: [:index, :show] before_action :find_article, only: [:show, :edit, :update, :destroy] def index @articles = Article.all.order(created_at: :desc) end def show end def edit end def new @article = Article.new end def create @article = Article.new(article_params) if @article.save redirect_to @article, notice: '作成しました' else render :new, alert: '作成できませんでした' end end def update if @article.update(article_params) redirect_to @article, notice: '更新しました' else render :edit, alert: '更新できませんでした' end end def destroy if @article.destroy redirect_to root_path, notice: '削除しました' else redirect_to root_path, alert: '削除できませんでした' end end private def find_article @article = Article.find(params[:id]) end def article_params params.require(:article).permit(:title, :body) end def move_to_index redirect_to action: :index unless user_signed_in? end end

views/articles/new.html.haml

.container %h1.text-center ブログの新規作成 .row.justify-content-center .col-md-6.mt-5.text-center = image_tag 'foodie.jpg', alt: '', height: '500px', width: '500px' = render 'form', article: @article

views/articles/_form.html.haml

= form_for article do |f| .form_group = f.label :title, "title", style: "margin-top: 10px;" = f.text_field :title, class: 'form_control' .form_group = f.label :body, "text" = f.text_area :body, rows: 10, class: 'form_control mt-1' %br = f.submit "新規作成", class: "btn btn-primary"

application_controller.rb

class ApplicationController < ActionController::Base before_action :authenticate_user! before_action :configure_permitted_parameters, if: :devise_controller? private def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up, keys: [:nickname]) end end

#試してみたこと
・binding.pryをかけて、パラメーターの中身を確認。

def create #binding.pry→結果① @article = Article.new(article_params) if @article.save redirect_to @article, notice: '作成しました' else render :new, alert: '作成できませんでした' end #binding.pry→結果② end

・結果①

Started POST "/articles" for ::1 at 2020-07-16 18:45:25 +0900 Processing by ArticlesController#create as HTML Parameters: {"authenticity_token"=>"4wrxi7CrlBg0MG6JMyna2jpkaU7IjdPzQOvD5r+lTLTi0Z/BOHcETPeJCi6f41gFs4fQpcVpv9WrUcufTukzuQ==", "article"=>{"title"=>"aaaaaaaa", "body"=>"aaaaaaaa"}, "commit"=>"新規作成"} User Load (0.4ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 ORDER BY `users`.`id` ASC LIMIT 1 From: /Users/laflora/projects/game_plan/app/controllers/articles_controller.rb:21 ArticlesController#create: 20: def create => 21: binding.pry 22: @article = Article.new(article_params) 23: if @article.save 24: redirect_to @article, notice: '作成しました' 25: else 26: render :new, alert: '作成できませんでした' 27: end 28: end [1] pry(#<ArticlesController>)> params => <ActionController::Parameters {"authenticity_token"=>"4wrxi7CrlBg0MG6JMyna2jpkaU7IjdPzQOvD5r+lTLTi0Z/BOHcETPeJCi6f41gFs4fQpcVpv9WrUcufTukzuQ==", "article"=>{"title"=>"aaaaaaaa", "body"=>"aaaaaaaa"}, "commit"=>"新規作成", "controller"=>"articles", "action"=>"create"} permitted: false> [2] pry(#<ArticlesController>)> article_params => <ActionController::Parameters {"title"=>"aaaaaaaa", "body"=>"aaaaaaaa"} permitted: true> [3] pry(#<ArticlesController>)> Started GET "/articles" for ::1 at 2020-07-16 18:48:12 +0900 [3] pry(#<ArticlesController>)> exit

・結果②

Started POST "/articles" for ::1 at 2020-07-16 18:49:30 +0900 Processing by ArticlesController#create as HTML Parameters: {"authenticity_token"=>"/wEYGKYPd3IjKc7U4+l80zHUgBm0VkZeydHk5V0xGuwSqwWt+Xy3HKyv4M9YuGOITBnKraE4vlkGEOLZbbGFdQ==", "article"=>{"title"=>"bbbbbbbbb", "body"=>"bbbbbbbbbbb"}, "commit"=>"新規作成"} User Load (0.7ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 ORDER BY `users`.`id` ASC LIMIT 1 Rendering articles/new.html.haml within layouts/application Rendered articles/_form.html.haml (Duration: 1.0ms | Allocations: 516) Rendered articles/new.html.haml within layouts/application (Duration: 2.5ms | Allocations: 1215) [Webpacker] Everything's up-to-date. Nothing to do Rendered layouts/_header.html.haml (Duration: 0.3ms | Allocations: 124) Rendered layouts/_notifications.html.haml (Duration: 0.1ms | Allocations: 21) From: /Users/laflora/projects/game_plan/app/controllers/articles_controller.rb:27 ArticlesController#create: 20: def create 21: @article = Article.new(article_params) 22: if @article.save 23: redirect_to @article, notice: '作成しました' 24: else 25: render :new, alert: '作成できませんでした' 26: end => 27: binding.pry 28: end [1] pry(#<ArticlesController>)> params => <ActionController::Parameters {"authenticity_token"=>"/wEYGKYPd3IjKc7U4+l80zHUgBm0VkZeydHk5V0xGuwSqwWt+Xy3HKyv4M9YuGOITBnKraE4vlkGEOLZbbGFdQ==", "article"=><ActionController::Parameters {"title"=>"bbbbbbbbb", "body"=>"bbbbbbbbbbb"} permitted: false>, "commit"=>"新規作成", "controller"=>"articles", "action"=>"create"} permitted: false> [2] pry(#<ArticlesController>)> article_params => <ActionController::Parameters {"title"=>"bbbbbbbbb", "body"=>"bbbbbbbbbbb"} permitted: true> [3] pry(#<ArticlesController>)> Started GET "/articles" for ::1 at 2020-07-16 18:56:06 +0900 [3] pry(#<ArticlesController>)> exit

・ストロングパラメーターも正しく働いて、パラメーターの中身は空っぽではないはずだと思うのですが、、怪しい記述が見つけられないので、どなたかご鞭撻のほどよろしくお願いいたします。。

#備考
削除機能は正しく動いています。
2020/07/17 追記
articles_controller.rbのストロングパラメーター(article_params)を以下のように記述し直して実行してみましたが、変化ありませんでした。binding.pryでみてみたら、idが取れていないようでしたので、:user_idと書き換えて試してみたのですが、同じ結果になりました。。

なぜid引っ張ってこれないのでしょうか?
お力貸していただけると大変有難いです。

def article_params params.require(:article).permit(:title, :body, :user) end
20: def create 21: @article = Article.new(article_params) => 22: binding.pry 23: if @article.save 24: redirect_to @article, notice: '作成しました' 25: else 26: render :new, alert: '作成できませんでした' 27: end 28: end [1] pry(#<ArticlesController>)> article_params => <ActionController::Parameters {"title"=>"どうも", "body"=>"はじめまして。"} permitted: true> [2] pry(#<ArticlesController>)> @article => #<Article:0x00007fd7a4d863b8 id: nil, title: "どうも", body: "はじめまして。", img: nil, user_id: nil, created_at: nil, updated_at: nil> [3] pry(#<ArticlesController>)>

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

自己解決

.merge(user_id: current_user.id)をストロングパラメーターに追記することで解決しました。

有難うございました!

投稿2020/07/16 16:19

ochibi1

総合スコア1

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問