LoginSignup
2
2

More than 3 years have passed since last update.

Railsのdeviseで新規登録するとき、親のモデル(belongs_toなもの)も一緒に作る方法

Last updated at Posted at 2019-05-07

環境

  • Rails 5.2.2
  • Ruby 2.5.3

前提

  • User belongs_to Organization
  • Organization has_many Users
  • Userを新規登録するとき、Organizationも一緒に作りたい(というか作れないとエラーで登録できない)

コード

class ApplicationController < ActionController::Base
  ...
  before_action :configure_permitted_parameters, if: :devise_controller?

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [organization_attributes: [:name]])
  end
end
# app/views/devise/registrations/new.html.erb
...
<% resource.organization ||= Organization.new %>
<%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= f.error_notification %>

  <div class="form-inputs">
    <%= f.input :email,
                required: true,
                autofocus: true ,
                input_html: { autocomplete: "email" }%>
    <%= f.input :password,
                required: true,
                hint: ("#{@minimum_password_length} characters minimum" if @minimum_password_length),
                input_html: { autocomplete: "new-password" } %>
    <%= f.input :password_confirmation,
                required: true,
                input_html: { autocomplete: "new-password" } %>

    <%= f.fields_for :organization do |organization_form| %>
      <%= organization_form.input :name %>
    <% end %>
  </div>

  <div class="form-actions">
    <%= f.button :submit, t("devise.sign_up") %>
  </div>
<% end %>
...

参考

https://github.com/plataformatec/devise#strong-parameters
https://stackoverflow.com/a/7987480/7824640

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2