Не удается заставить пользователей создать собственное сообщение с приглашением на разработку

В моем приложении есть две пользовательские модели: «Участник» и «Член». Я пытаюсь разрешить им включать собственное сообщение, когда они приглашают других участников/участников через Devise Invitable. Однако я не могу заставить его работать.

Я следую этому официальное руководство, поэтому я внес следующие изменения, чтобы переопределить Devise Invitable Controller, но при использовании pry кажется, что этот пользовательский контроллер остается нетронутым при отправке приглашать. Что я делаю неправильно:

контроллеры/участники/invitations_controller.rb

class Participants::InvitationsController < Devise::InvitationsController
      before_action :update_sanitized_params, only: :update

  def create
    binding.pry
    @from    = params[:from]
    @subject = params[:invite_subject]
    @content = params[:invite_content]

    @participant = Participant.invite!(params[:user], current_member) do |u| #XXX Check if :user should be changed
      u.skip_invitation = true
    end

    ParticipantInvitationNotificationMailer.invite_message(@participant, @from, @subject, @content).deliver if @participant.errors.empty?
    @participant.invitation_sent_at = Time.now.utc # mark invitation as delivered

    if @participant.errors.empty?
      flash[:notice] = "successfully sent invite to #{@participant.email}"
      respond_with @participant, :location => root_path
    else
      render :new
    end
  end

  def update
    respond_to do |format|
      format.js do
        invitation_token = Devise.token_generator.digest(resource_class, :invitation_token, update_resource_params[:invitation_token])
        self.resource = resource_class.where(invitation_token: invitation_token).first
        resource.skip_password = true
        resource.update_attributes update_resource_params.except(:invitation_token)
      end
      format.html do
        super
      end
    end
  end

  protected

  def update_sanitized_params
    devise_parameter_sanitizer.permit(:accept_invitation, keys: [:password, :password_confirmation, :invitation_token, :username])
  end


end

config/routes.rb

Rails.application.routes.draw do
  devise_for :members, controllers: { invitations: "members/invitations" }
  devise_for :participants, controllers: { invitations: "participants/invitations" }
end

models/participant.rb

class Participant < ApplicationRecord
  attr_reader :raw_invitation_token
end

почтовые программы/notification_mailer.rb

class NotificationMailer < ApplicationMailer
  def invite_message(user, from, subject, content)
  @user = user
  @token = user.raw_invitation_token
  invitation_link = accept_user_invitation_url(:invitation_token => @token)

  mail(:from => from, :bcc => from, :to => @user.email, :subject => subject) do |format|
    content = content.gsub '{{first_name}}', user.first_name
    content = content.gsub '{{last_name}}', user.last_name
    content = content.gsub '{{full_name}}', user.full_name
    content = content.gsub('{{invitation_link}}', invitation_link)
      format.text do
        render :text => content
      end
    end
  end
end

Если я отправлю приглашение: с Participant.invite!({:email => '[email protected]'}, Member.first), приглашение будет отправлено через почтовую программу по умолчанию, как показано в консоли, но не через мою новую почтовую программу. Зачем?

  Rendering /Users/andres/.rvm/gems/ruby-2.4.0@pixiebob/gems/devise_invitable-1.7.1/app/views/devise/mailer/invitation_instructions.html.erb
  Rendered /Users/andres/.rvm/gems/ruby-2.4.0@pixiebob/gems/devise_invitable-1.7.1/app/views/devise/mailer/invitation_instructions.html.erb (0.6ms)
  Rendering /Users/andres/.rvm/gems/ruby-2.4.0@pixiebob/gems/devise_invitable-1.7.1/app/views/devise/mailer/invitation_instructions.text.erb
  Rendered /Users/andres/.rvm/gems/ruby-2.4.0@pixiebob/gems/devise_invitable-1.7.1/app/views/devise/mailer/invitation_instructions.text.erb (0.8ms)

person alopez02    schedule 23.02.2017    source источник


Ответы (1)


Наконец-то я смог решить эту проблему.

Это оказалось ошибкой новичка. Я думал, что вызов метода invite! будет иметь какое-то отношение к пользовательскому методу create в пользовательском контроллере приглашений.

Я должен был, конечно, добраться до метода create по указанному маршруту и ​​в этом методе предотвратить приглашение! метод отправки электронной почты через почтовую программу по умолчанию, используя приведенный ниже код (как четко указано в документации Devise Invitable):

  @participant = Participant.invite!({:email => @invitation_draft.email}, current_member) do |u|
    u.skip_invitation = true
  end  

После этого мы можем вызывать любой пользовательский мейлер в методе create.

person alopez02    schedule 06.03.2017