Ryan Grush
Ryan Grush

Reputation: 2128

Rails + Devise, registration form with nested attributes not creating associated record

I have a simple form_for using Devise but I'm having issues with nested attributes:

routes.rb

devise_for :guest, controllers: {
  registrations: 'guests/registrations'
}

devise/registrations/new.html.erb

<%= form_for @guest, url: guest_registration_path do |f| %>
  <%= f.email_field :email %>
  <%= f.text_field :first_name %>
  <%= f.text_field :last_name %>
  <%= f.password_field :password %>
  <%= f.password_field :password_confirmation %>
  <%= f.check_box :plus_one %>
  <%= f.fields_for :invite do |i| %>
    <%= i.text_field :first_name %>
    <%= i.text_field :last_name %>
  <% end %>
  <%= f.submit "Log In" %>

guests/registrations_controller.rb

class Guests::RegistrationsController < Devise::RegistrationsController

  def new
    @guest = Guest.new
    @guest.invite = Invite.new
  end

  protected

    def sign_up_params
      params.require(:guest).permit!
    end

end

guest.rb

class Guest < ApplicationRecord

  devise :database_authenticatable, :registerable, :recoverable, :trackable

  has_one :invite

  accepts_nested_attributes_for :invite

end

invite.rb

class Invite < ApplicationRecord

  belongs_to :guest

end

When it attempts to create the Guest using the nested attributes I get this error -

ActiveRecord::RecordInvalid: Validation failed: Invite guest must exist

I've used forms with nested attributes in Rails before using this same setup so I'm wondering if it some Devise specific method I'm missing. It appears as though its not creating the Invite record with the correct guest_id and I can't figure out what the issue is.

Upvotes: 2

Views: 657

Answers (1)

Thanh
Thanh

Reputation: 8604

It seems you are using Rails 5, belongs_to requires association record must be exist by default. If so, then you need to add inverse_of to your associations:

class Guest
  has_one :invite, inverse_of: :guest
end

class Invite
  belongs_to :guest, inverse_of: :invite
end

Upvotes: 2

Related Questions