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

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

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

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

Ruby on Rails

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

Q&A

解決済

1回答

1110閲覧

postしてもモデルにデータがsaveできない

takuma1229

総合スコア11

Ruby

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

Ruby on Rails

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

0グッド

0クリップ

投稿2021/06/09 02:32

前提・実現したいこと

Railsでwebサービスを作っています。
userのサインアップが完了した(usersモデルにデータをsaveした)後に、そのuserの詳細データを入力させuserモデルとは別のDetailsモデルにsaveする機能を作っています。(下述するuserコントローラのコードを読んで頂いた方が、実現したいことが分かりやすいかもしれません)

デバッグを見ると必要なDetailsの項目とそれに対応する値は送信できているようです。

Debug

1--- !ruby/object:ActionController::Parameters 2parameters: !ruby/hash:ActiveSupport::HashWithIndifferentAccess 3 authenticity_token: NdZE8VVVUbEafANhWLU+UqQcF6Ipk99Gc0I8SO1mvts1JOWW/dXBDUUEhsjU2ujNNUw/GWIgg== 4 mother_tongue: Japanese 5 japanese_level: Capable of daily conversation | 日常会話ができる 6 gender: he/him | 男性 7 region: Europe | ヨーロッパ 8 purpose: Entrance Exam | 受験 9 self_introduction: adfafasd 10 sns_1: dfasdfas 11 sns_2: adfafasf 12 sns_3: fdasfsadff 13 user_id: '2' 14 commit: Send 15 controller: users 16 action: details_create 17permitted: false

それにも関わらず、どうやらDetailsモデルへのsaveができていないようです。
この「Detailsモデルへのsave」がなぜ期待通り行われないのかを教えていただきたいです。

程度の低い質問でしたら申し訳ございません。
また、回答に必要な情報に不足があれば、お手数ですがご指摘いただければ、随時追記いたします。

よろしくお願いいたします。

該当のソースコード

ruby

1[users_controller.rb] 2class UsersController < ApplicationController 3 4 def show 5 @user = User.find(params[:id]) 6 end 7 8 def new 9 @user = User.new 10 end 11 12 def create 13 @user = User.new(user_params) 14 if @user.save 15 log_in @user 16 flash[:success] = "Welcome to INTE! Your account has been creaeted." 17 redirect_to details_path 18 else 19 render 'new' 20 end 21 end 22 23 def details 24 25 end 26 27 def details_create 28 @details = Detail.new(detail_params) 29 if @details.save //ここが問題の箇所です。root_pathへのredirectが行われずdetailsにrenderされます。 30 redirect_to root_path 31 else 32 render 'details' 33 end 34 end 35 36 37 private 38 39 def user_params 40 params.require(:user).permit(:name, :email, :image, :password, :password_confirmation) 41 end 42 43 def detail_params 44 params.permit(:authenticity_token, :user_id, :mother_tongue, :japanese_level, :english_level, 45 :gender, :region, :purpose, :self_introduction, :sns_1, :sns_2, :sns_3) 46 end 47 48end 49

html

1[details.html.erb] 2<% provide(:title, "user detail") %> 3 4<div class="user-detail-wrapper"> 5 <div class="introduction"> 6 <h3>①Authorize your account via sent Email.</h3> 7 <h3>②Let's register your user informations!<br>You can change it later.</h3> 8 </div> 9 10 <div class="row user-detail-forms"> 11 <div class="col-md-6 col-md-offset-3"> 12 <%= form_with(model: @detail, local: true) do |f| %> 13 14 15 <%= f.label :mother_tongue, "Mother Tongue" %> 16 <%= f.select :mother_tongue, [["English", "English"], ["Japanese", "Japanese"], 17 ["Other","other"]], include_blank: "Please select.", class:"form-control" %> 18 19 <%= f.label :japanese_level, "Japanese Level" %> 20 <%= f.select :japanese_level, [["Beginner | 初心者", "Beginner | 初心者"], ["Capable of quite basic communication | 簡単な会話ならできる", "Capable of quite basic communication | 簡単な会話ならできる"], 21 ["Capable of daily conversation | 日常会話ができる","Capable of daily conversation | 日常会話ができる"], ["Capable of advanced conversation | 難しい内容の会話ができる","Capable of advanced conversation | 難しい内容の会話ができる"], ["Almost native level | ネイティブとほとんど同レベル","Almost native level | ネイティブとほとんど同レベル"], 22 ["Native | ネイティブ","Native | ネイティブ"]], include_blank: "Please select.", class:"form-control" %> 23 24 25 <%= f.label :gender, "Gender(optional)" %> 26 <%= f.select :gender, [["he/him | 男性", "he/him | 男性"], ["she/her | 女性", "she/her | 女性"], 27 ["they/them | その他","they/them | その他"], ["I don't want to tell | 言いたくない","I don't want to tell | 言いたくない"]], include_blank: "Please select.", class:"form-control" %> 28 29 <%= f.label :region, "Region" %> 30 <%= f.select :region, [["Asia | アジア", "Asia | アジア"], ["Europe |ヨーロッパ", "Europe | ヨーロッパ"], 31 ["Africa | アフリカ","Africa | アフリカ"], ["North/Central America | 北/中央アメリカ","North/Central America | 北/中央アメリカ"], ["South America | 南アメリカ","South America | 南アメリカ"], 32 ["Oceania | オセアニア","Oceania | オセアニア"], ["Other | その他","Other | その他"]], include_blank: "Please select.", class:"form-control" %> 33 34 <%= f.label :purpose, "Purpose of Learning" %> 35 <%= f.select :purpose, [["Business | 仕事", "Business | 仕事"], ["School Classes | 学校の授業", "School Classes | 学校の授業"], 36 ["Entrance Exam | 受験","Entrance Exam | 受験"], ["Trip | 旅行","Trip | 旅行"], ["Want to talk with Foreingers | 外国の人と話したい","Want to talk with Foreingers | 外国の人と話したい"], 37 ["Qualifying Exam | 資格試験","Qualifying Exam | 資格試験"], ["Hobby | 趣味","Hobby | 趣味"], ["Other | その他", "Other | その他"]], include_blank: "Please select.", class:"form-control" %> 38 39 <%= f.label :self_introduction, "Self Introduction" %> 40 <%= f.text_area :self_introduction, class: 'form-control self-intro', placeholder: "It is recommended that you write in simple English." %> 41 42 <%= f.label :sns_1, "URL of Your SNS 1 (optional)" %> 43 <%= f.text_field :sns_1, class: 'form-control' %> 44 45 <%= f.label :sns_2, "URL of Your SNS 2 (optional)" %> 46 <%= f.text_field :sns_2, class: 'form-control' %> 47 48 <%= f.label :sns_3, "URL of Your SNS 3 (optional)" %> 49 <%= f.text_field :sns_3, class: 'form-control' %> 50 51 <%= f.text_field :user_id, type: "hidden", value: "#{current_user.id}" %> 52 53 54 <%= f.submit "Send", class: "btn btn-primary create" %> 55 <% end %> 56 </div> 57 </div> 58</div>

ruby

1[routes.rb] 2Rails.application.routes.draw do 3 4 get 'sessions/new' 5 root 'static_pages#language' 6 get '/home_jp', to:'static_pages#home_jp' 7 get '/home_en', to:'static_pages#home_en' 8 get '/signup', to:'users#new' 9 get '/details', to:'users#details' 10 post '/details', to:'users#details_create' 11 get '/login', to:'sessions#new' 12 post '/login', to:'sessions#create' 13 delete '/logout', to:'sessions#destroy' 14 # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html 15 resources :users 16end 17

ruby

1[detail.rb] 2class Detail < ApplicationRecord 3 belongs_to :user 4 validates :mother_tongue, presence: true 5 validates :japanese_level, presence: true 6 validates :english_level, presence: true 7 validates :region, presence: true 8 validates :purpose, presence: true 9 validates :self_introduction, presence: true, length: {maximum:300} 10end 11

補足情報(FW/ツールのバージョンなど)

Rails 6.0.3
Ruby 2.6.3
AWS cloud9を使用

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

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

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

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

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

guest

回答1

0

ベストアンサー

そういうときのために、error内容を表示するようにしましょう。
とりあえず if @details.save! と ! 付きにしてやってみてください。
何が原因か表示されると思います

そうそう、、、
saveするのは一つなのですから、@detail と単数形にしたほうが良いです。人がbugります。

投稿2021/06/09 02:41

編集2021/06/09 02:42
winterboum

総合スコア23401

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

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

takuma1229

2021/06/09 03:24

回答ありがとうございます。 if @detail.save!としてみたら、English Levelの項目がHTMLから抜けているため、バリデーションに引っかかっていることが分かりました! save!とすると失敗した場合にエラーを返してくれるのですね。 本当に助かりました。ありがとうございます!
winterboum

2021/06/09 04:04

! すると例外でとまってしまいますから、通常はviewの方で model.errors の内容を表示するようにします
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.46%

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

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

質問する

関連した質問