我在一個用戶郵件檔案中有一個before動作,它應該是在user上的一個列被設定為true或false時停止郵件的發送。然而當前的用戶目前是不可用的。我明白原因,但想知道是否有辦法做到這一點。
我想避免在每個郵件方法的頂部添加check_if_users_can_receive_mailers。
before_action :check_if_users_can_receive_mailers
#發送郵件的方法
私有
def check_if_users_can_receive_mailers
current_user.send_mailers?
end
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
你必須使當前用戶作為一個屬性或類變數可用。最直接的方法是像這樣的:
class MailerBase < ActionMailer::Base
before_action :check_if_users_can_receive_mailersattr_accessor :user
def initialize(user)
@user = user
end
私有
def check_if_users_can_receive_mailers
user.send_mailers?
end>
end>
class SomeMailerClass < MailerBase
end
uj5u.com熱心網友回復:
在Rails中,只有你的控制器和視圖可以感知請求。在你的應用程式中,郵件、模型和其他類都不是,它們不能獲得當前用戶,因為它們不能訪問會話,也不能訪問current_user方法,該方法是混入你的控制器(和視圖背景關系)的一個輔助方法。
如果你的郵件程式需要知道當前用戶的情況,最合理的方法是將該資訊傳遞給郵件程式:
class UserMailer < ApplicationMailer
def intialize(user)
@user = user
end
end end
然而,一個郵件程式應該只有一個作業--發送郵件,它不應該質疑是否應該完成這個作業。確定是否應該向用戶發送郵件應該在其他地方完成。你可以把這個邏輯放在控制器中,甚至最好放在一個服務物件中:
# app/notifiers/user_notifier.rb
class UserNotifier
def initialize(user, event:)
@user = user
@event = event
end = 事件
def notify
if @user.wants_email?
spam_user!
結束。
send_in_app_notification
end end
def self.notify(user, event:)
new(user, event:)
結束。
私有的
def spam_user!
# ...
end
def send_in_app_notification
# ...
end
end end
class ThingsController>
def create
@thing = Thing.new
if @thing.save
UserNotifier.notify(current_user, event: :thing_created)
redirect_to @thing[/span].
else
渲染:new
end
end
end end
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/307037.html
標籤:
上一篇:用戶在注冊時發表第一個嵌套帖子,Rubyonrails
下一篇:在C#中讓按鈕在5秒后永遠出現
