【问题标题】:User with admin role can have many hotels, but how can an admin invite a user for just one of its hotels?具有管理员角色的用户可以拥有多家酒店,但管理员如何仅邀请用户入住其中一家酒店?
【发布时间】:2020-02-25 12:16:42
【问题描述】:

上下文 我无法理解以下内容:

  • User 和 Hotel 之间通过连接表 User_Hotel 存在多对多关系。
  • 使用 devise 创建的用户具有管理员角色
  • 具有管理员角色的用户可以创建许多酒店
  • 具有管理员角色的用户应该能够邀请其他用户到特定酒店(例如,不是所有酒店)。我正在使用 devise-invitable gem 发送邀请。

问题 我为用户/邀请设置了路由、模型和控制器,但出了点问题:

  1. 因为我的hotel_id 参数未正确发送到我的invitations_controller。查看错误信息: Couldn't find Hotel without an ID. params sent: {"format"=>"109"}
  2. 我不确定是否/如何在受邀的特定酒店用户之间建立联系?

观看次数/酒店/演出

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

路线

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

  resources :hotels do
    resources :users
  end
end

模型

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

控制者/用户/邀请

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

【问题讨论】:

    标签: ruby-on-rails devise devise-invitable


    【解决方案1】:

    IDK,如果被邀请到酒店的用户需要接受或不接受。

    如果需要接受:

    您需要一个表格来存储邀请,您将在其中存储user a 邀请到user bhotel a。然后你需要inviter_idinvited_idhotel_id。当用户接受邀请时,您将在与酒店和用户相关的中间表中添加一条记录。

    另一种方法是在中间表中添加一个标志来控制哪些被接受,哪些还没有,并在关系上添加一个默认范围以仅获得接受。

    如果用户将直接添加到酒店:

    你只需要这样做:

    @hotel = Hotel.find(params[:hotel_id])
    @user = User.new
    @user.hotels << @hotel
    

    【讨论】:

    • 感谢您的详细反馈。我正在使用 devise-invitable gem,所以我相信 gem 会为我做到这一点。我已经在使用@hotel = Hotel.find(params[:hotel_id]),但收到错误消息Couldn't find Hotel without an ID. params sent: {"format"=&gt;"109"}
    猜你喜欢
    • 1970-01-01
    • 2013-10-05
    • 1970-01-01
    • 2016-12-17
    • 1970-01-01
    • 1970-01-01
    • 2012-10-09
    • 2018-04-29
    • 2017-05-22
    相关资源
    最近更新 更多