ユーザーが会社に所属し、企業に多数のユーザーがいることをアプリに構造化したいと考えています。会社名は、私のDevise Sign Upフォームに含まれている必要があります。ここでRailsを使用して、親会社を募集しています。
は私のコードです:
company.rb
class Company < ApplicationRecord
has_many :users
end
user.rb
class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
belongs_to :company
accepts_nested_attributes_for :company
end
registrations_controller.rb
上記のコードを使用class RegistrationsController < Devise::RegistrationsController
before_action :configure_sign_up_params, only: [:create]
# GET /resource/sign_up
def new
build_resource({})
set_minimum_password_length
resource.build_company
yield resource if block_given?
respond_with self.resource
end
# POST /resource
def create
build_resource(sign_up_params)
resource.save
if resource.persisted?
if resource.active_for_authentication?
set_flash_message :notice, :signed_up if is_flashing_format?
sign_up(resource_name, resource)
respond_with resource, location: after_sign_up_path_for(resource)
else
set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_flashing_format?
expire_data_after_sign_in!
respond_with resource, location: after_inactive_sign_up_path_for(resource)
end
else
clean_up_passwords resource
set_minimum_password_length
respond_with resource, location: new_api_v1_public_members_user_registration_path(beta_token: params[:beta_token])
end
end
def configure_sign_up_params
devise_parameter_sanitizer.permit(:sign_up) do |user_params|
user_params.permit(:email, :password, :password_confirmation, company: [ :name])
end
end
end
_form.haml
...
= f.text_field :email
= f.fields_for :company do |c|
= c.text_field :name
= f.password_field :password, autocomplete: "off", autofocus: true
= f.password_field :password_confirmation, autocomplete: "off"
...
、私の(私のログファイルごとに)ルートを作成するすべての値を送信します。しかし、当社の親会社の価値は維持されていません。これにより、Company.name値を空白にすることができないため、フォームの検証が失敗します。
は、どのように私はこのコードを変更しない:子供(ユーザー)フォーム
- 保存親会社(会社)、それを保存するときに、ユーザーにCompany.id値を割り当てます。ユーザーモデルの 'company_id'属性を入力して
ご協力いただければ幸いです。
ネストされたフォームの宝石https://github.com/ryanb/nested_formを使用しようとしましたか? –