前提・実現したいこと
deviseの新規ユーザー登録画面で2テーブルに情報を送りたい。
1つはユーザー情報、もう1つのテーブルは会社情報
ここに質問の内容を詳しく書いてください。
現在参考記事を頼りに下記のコードを書きました。
user.rb
user.rb
1 has_one :campany 2 accepts_nested_attributes_for :campany
campany.rb
campany.rb
1belongs_to :user
class Users::RegistrationsController < Devise::RegistrationsController
class
1 before_action :configure_sign_up_params, only: [:create, :new, :new_campany] 2 3 def new_campany 4 @user = User.new 5 @user.campany.new 6 end 7 8 def configure_sign_up_params 9 devise_parameter_sanitizer.permit(:sign_up, 10 keys: [:name, :category_id, campany_attributes: [:campany_name, :campany_logo, :category_id, :campany_url, :tel, :staff_last_name_kana, :staff_first_name_kana]]) 11 end
発生している問題・エラーメッセージ
undefined method `new' for nil:NilClass
該当のソースコード
class Users::RegistrationsController < Devise::RegistrationsController
class
1 before_action :configure_sign_up_params, only: [:create, :new, :new_campany] 2 3 def new_campany 4 @user = User.new 5 @user.campany.new 6 end 7 8 def configure_sign_up_params 9 devise_parameter_sanitizer.permit(:sign_up, 10 keys: [:name, :category_id, campany_attributes: [:campany_name, :campany_logo, :category_id, :campany_url, :tel, :staff_last_name_kana, :staff_first_name_kana]]) 11 end
試したこと
binding.pryを行ったが、やはり@user.campany.newでインスタンスが生成されない
[1] pry(#<Users::RegistrationsController>)> params => <ActionController::Parameters {"controller"=>"users/registrations", "action"=>"new_campany"} permitted: false> [2] pry(#<Users::RegistrationsController>)> @user => #<User id: nil, name: nil, avater: nil, category_id: nil, created_at: nil, updated_at: nil, email: ""> [3] pry(#<Users::RegistrationsController>)> Campany => Campany(id: integer, name: string, campany_logo: binary, category_id: integer, campany_url: string, email: string, tel: integer, staff_last_name_kana: string, staff_first_name_kana: string, created_at: datetime, updated_at: datetime, encrypted_password: string, reset_password_token: string, reset_password_sent_at: datetime, remember_created_at: datetime) [4] pry(#<Users::RegistrationsController>)> @user.campany.new NoMethodError: undefined method `new' for nil:NilClass
だいぶ調べたのですが、ネストさせてレコードを作成する際の方法は@user.campany.buil or @user.campany.newの記述で統一されていました。
deviseのデフォルト以外のカラム追加もエラー出ていないので問題内容に思います。
どうぞご教授よろしくお願い申し上げます。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。