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

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

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

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

Q&A

解決済

2回答

253閲覧

ネストさせたフォームのDBへの登録

退会済みユーザー

退会済みユーザー

総合スコア0

Ruby on Rails 5

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

0グッド

0クリップ

投稿2019/08/01 03:56

前提・実現したいこと

Railsでdeviseを使ったユーザーの新規登録をする際に、
profileモデルにもデータを保存したいです。

発生している問題・エラーメッセージ

deviseのコントローラーをいじって、フォームをネストさせるところまではいきましたが
DBへの保存がうまくいきません。

特にエラーにはならず、userのみsaveされ
profilesテーブルにはレコードがない状態になっています。

該当のソースコード

registrations_controller.rb

class Users::RegistrationsController < Devise::RegistrationsController # before_action :configure_sign_up_params, only: [:create] # before_action :configure_account_update_params, only: [:update] def new super @user = User.new @user.build_profile end def create super @user = User.new(configure_sign_up_params) # binding.pry @user.save end protected # If you have extra params to permit, append them to the sanitizer. def configure_sign_up_params devise_parameter_sanitizer.permit(:sign_up, keys: [profile_attributes: [:company_name, :rep, :phone_number]]) end end

model/user.rb

class User < ApplicationRecord devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable, :lockable, :timeoutable has_many :orders has_one :profile accepts_nested_attributes_for :profile end

model/profile.rb

class Profile < ApplicationRecord belongs_to :user end

views/devise/registrations/new.html.haml

.devise-container %h2.devise-title 新規登録 = form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| = render "devise/shared/error_messages", resource: resource = f.fields_for :profiles do |profile| .field = profile.label :会社名 %br/ = profile.text_field :company_name, class: "email-field" .field = profile.label :ご担当者様名 %br/ = profile.text_field :rep, class: "email-field" .field = profile.label :電話番号 %br/ = profile.telephone_field :phone_number, class: "email-field" .field = f.label :メールアドレス %br/ = f.email_field :email, autofocus: true, autocomplete: "email", class: "email-field" .field = f.label :パスワード(※4〜8文字以内) %br/ = f.password_field :password, autocomplete: "new-password", class: "password-field" .field = f.label :パスワード(確認) %br/ = f.password_field :password_confirmation, autocomplete: "new-password", class: "password-field" .actions = f.submit "登録する", class: "submit-btn" = render "devise/shared/links"

SQL文

Started POST "/users" for ::1 at 2019-08-01 12:39:57 +0900 Processing by Users::RegistrationsController#create as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"xVHalOZRp95d93PliWP3JTWQuKnMfE0W1lZhrDVE9WEyqbQw+AaRP8gEudj/pMpU1qvJQz6BEqRcccSh/Rghvg==", "user"=>{"profiles"=>{"company_name"=>"(株)中島商店", "rep"=>"田中", "phone_number"=>"09012345678"}, "email"=>"aiueo@gmaill.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"登録する"} Unpermitted parameter: :profiles (0.2ms) BEGIN ↳ app/controllers/users/registrations_controller.rb:16 User Exists (0.3ms) SELECT 1 AS one FROM `users` WHERE `users`.`email` = BINARY 'aiueo@gmaill.com' LIMIT 1 ↳ app/controllers/users/registrations_controller.rb:16 User Create (6.7ms) INSERT INTO `users` (`email`, `encrypted_password`, `created_at`, `updated_at`) VALUES ('aiueo@gmaill.com', '$2a$11$YL/Cmi/i1HQo/lg3kYET1eqxOWjG6cEVewgS2gWu4d9aLGw4ByFgW', '2019-08-01 03:39:57', '2019-08-01 03:39:57') ↳ app/controllers/users/registrations_controller.rb:16 (1.1ms) COMMIT ↳ app/controllers/users/registrations_controller.rb:16 Redirected to http://localhost:3000/orders/new (0.1ms) BEGIN ↳ app/controllers/users/registrations_controller.rb:19 (0.2ms) ROLLBACK ↳ app/controllers/users/registrations_controller.rb:19 Completed 302 Found in 160ms (ActiveRecord: 8.6ms)

試したこと

binding.pryでデバック
params[:user][:profiles][:カラム名]で値は取り出せるので、あとはDBへの保存のみかなと思います
profilesテーブルのカラム名を見直しましたが、誤字は無し
user_idもforeign_keyで入れているので、原因がわかりません。

よろしくお願いします。

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

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

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

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

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

guest

回答2

0

ベストアンサー

以下の二点を試したところ、解決しました。

  • application_controller.rbにもストロングパラメーターを追加する
  • コントローラーでbuildせずにfields_for内で直接buildさせる

application_controller.rb

class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :configure_permitted_paramaters, if: :devise_controller? private def configure_permitted_paramaters devise_parameter_sanitizer.permit(:sign_up, keys: [profile_attributes: [:company_name, :rep, :phone_number]]) end end

views/devise/registrations/new.html.haml

〜中略〜 = f.fields_for :profile, resource.build_profile || Profile.new do |profile| 〜中略〜

投稿2019/08/04 03:11

退会済みユーザー

退会済みユーザー

総合スコア0

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

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

0

def configure_sign_up_params devise_parameter_sanitizer.permit(:sign_up, profile_attributes: [:company_name, :rep, :phone_number]) end

としてみたらどうでしょう。
device絡むとprofile_attributes:が無視される可能性あるので、駄目かも
その時は deviceの達人にお出まし頂くか、達人に笑われても良ければ別案を。

投稿2019/08/01 07:28

winterboum

総合スコア23329

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

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

退会済みユーザー

退会済みユーザー

2019/08/01 08:00

ご回答ありがとうございます。 試してみましたが、unknown keyword: profile_attributesとなってしまいました、、 関係ないかもしれないですが、個人的に気になっているのはhamlの = f.fields_for :profiles do |profile| この部分で、自分はモデルの指定を:profileかなと思ったのですが(参考にした記事でも単数形だった) profilesにしないとbuildされたフォームが出現しません。 profilesモデルなんて無いよ、って意味でパラメーターが渡っていないという可能性は無いでしょうか。 重ね重ねすみません。
winterboum

2019/08/01 13:14

> profilesにしないとbuildされたフォームが出現しません ですが = f.fields_for :profile do |profile|  と書きました? = f.fields_for :profile do |profile_form|  にしてみてください
退会済みユーザー

退会済みユーザー

2019/08/04 03:12

変数を変えてみましたが、うまく保存ができませんでした。 fields_for内で直接buildすることで解決ができました。 色々と教えて頂き、ありがとうございました!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問