【问题标题】:Devise_invitable, how to invite users to one hotel and not all?Devise_invitable,如何邀请用户到一个酒店而不是全部?
【发布时间】:2019-10-31 08:31:11
【问题描述】:

在 user.admin has_many 酒店的情况下,有没有办法只邀请用户到 1 家酒店? (例如,用户和酒店之间的多对多关系,加入 UserHotel 表)。

更具体地说,我遇到的第一个问题是我无法在 users/invitations_controller 中正确插入 hotel_id 参数。

  • 错误信息:Couldn't find Hotel without an ID. params sent: {"format"=>"109"}

请在下面找到我当前的代码=>

观看次数/酒店/演出

<%= 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

【问题讨论】:

  • params 变量里面是什么?

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


【解决方案1】:

将此代码添加到app/models/user.rb:

accepts_nested_attributes_for :user_hotels

然后:

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

您可以添加自己的验证以防止重复输入。

【讨论】:

  • 感谢您的回答。参数仍然保留params sent: {"format"=&gt;"109"} 代码的这个附加结果是app/controllers/users/invitations_controller.rb:5: syntax error, unexpected '}', expecting =&gt; ...rks_attributes: {[hotel: @hotel]} ) ... ^
  • 抱歉,花括号放错了地方
  • 感谢您的回复,这让我更近了一步:)。使用User.new(user_hotels_attributes:[{hotel:@hotel}]),我确实没有收到错误消息。尽管如此,酒店参数仍未正确发送到新操作(例如 {"format"=&gt;"109"} 而不是 id=&gt;109
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多