我正在使用Rails创建提醒应用。我创建了一个发送彩信的notify
操作。我现在想要设置应用程序,以便当用户创建新提醒时,它还会执行notify
操作。但是,我是Rails的新手,不太清楚从哪里开始。
创建新提醒时可以执行通知操作吗?
notifications_controller.rb
require 'twilio-ruby'
class NotificationsController < ApplicationController
skip_before_action :verify_authenticity_token
def notify
client = Twilio::REST::Client.new 'account_sid', 'auth_token'
message = client.messages.create from: '+18588779747', to: current_user.phone_number, body: 'First ever MyMedy notifcation test.'
render plain: message.status
end
end
reminders_controller.rb
class RemindersController < ApplicationController
before_action :set_reminder, only: [:show, :edit, :update, :destroy]
....
# GET /reminders/new
def new
@reminder = Reminder.new
end
def create
@reminder = current_user.reminders.new(reminder_params)
respond_to do |format|
if @reminder.save
format.html { redirect_to @reminder, notice: 'Reminder was successfully created.' }
format.json { render action: 'show', status: :created, location: @reminder }
else
format.html { render action: 'new' }
format.json { render json: @reminder.errors, status: :unprocessable_entity }
end
end
end
的routes.rb
Medy::Application.routes.draw do
devise_for :users
resources :reminders
root 'reminders#index'
post 'notifications/notify' => 'notifications#notify'
答案 0 :(得分:4)
Rails控制器操作按设计耦合到路径:它们是您的应用程序的入口点,通过使用某些HTTP方法命中某些URL来触发。在你的情况下,你真的不希望这两个动作是相同的(因为其中一个需要创建一个提醒而另一个不需要)。你真正想要的是另一个处理MMS消息发送的对象,以及从两个控制器调用的对象:
<强> notifications_controller.rb 强>
def notify
message = MyNotifier.notify(current_user, "My message")
render plain: message.status
end
<强> reminders_controller.rb 强>
...
if @reminder.save
MyNotifier.notify(current_user, "My message")
...
或类似的东西,然后让你的班级:
<强> my_notifier.rb 强>
class MyNotifier
def self.notify(user, message)
client = Twilio::REST::Client.new YOUR_CLIENT_ID, YOUR_CLIENT_SECRET
client.messages.create from: '+18588779747', to: user.phone_number, body: message
end
end