2

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.

1
  • It looks like if I flip Guest to belongs_to and Invite to has_one it creates both correctly. Is there a way to do it the original way I had it?
    – Ryan Grush
    Feb 2, 2018 at 4:02

1 Answer 1

2

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
1
  • That works! Thank you, I was really stumped on that one.
    – Ryan Grush
    Feb 2, 2018 at 15:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.