0
votes

In the context where a user.admin has_many hotels, is there a way to invite a user to 1 hotel only? (e.g. many-to-many relationship between user and hotel, with join UserHotel table).

More concretely, the first problem I am encountering is that I am not able to properly insert the hotel_id param in the users/invitations_controller.

  • Error message:Couldn't find Hotel without an ID. params sent: {"format"=>"109"}

Please find my current code below=>

views/hotels/show

<%= link_to "invite new user", new_user_invitation_path(@hotel) %>

routes

Rails.application.routes.draw do
  devise_for :users, controllers: {
    invitations: 'users/invitations'
  }

  resources :hotels do
    resources :users
  end
end

models

class User < ApplicationRecord
  has_many :user_hotels, dependent: :destroy
  has_many :hotels, through: :user_hotels
  enum role: [:owner, :admin, :employee]
  after_initialize :set_default_role, :if => :new_record?

  def set_default_role
    self.role ||= :admin
  end

  devise :invitable, :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable, :invitable
end

class UserHotel < ApplicationRecord
  belongs_to :hotel
  belongs_to :user
end

class Hotel < ApplicationRecord
  has_many :user_hotels, dependent: :destroy
  has_many :users, through: :user_hotels

  accepts_nested_attributes_for :users, allow_destroy: true, reject_if: ->(attrs) { attrs['email'].blank? || attrs['role'].blank?}
end

controllers/users/invitations

class Users::InvitationsController < Devise::InvitationsController
  def new
    @hotel = Hotel.find(params[:hotel_id])
    @user = User.new
    How to build the join table UserHotel when inviting?
  end
end
1
what is inside the params variable?Moeen

1 Answers

0
votes

add this code to app/models/user.rb:

accepts_nested_attributes_for :user_hotels

and then:

User.new(user_hotels_attributes: [{ hotel: @hotel }])

you can add your own validations to prevent duplicate entry.