我已经在我的RoR应用中设置了Action Mailer,我希望它能够在他们的" MatchCenter"的内容中向用户发送电子邮件。页面更改。
MatchCenter根据用户通过微博提供的条件,使用易趣的API显示项目。这意味着由于外部来源eBay,结果不断变化,而不是用户方面的任何行动。
我正在考虑创建一个MatchCenter控制器并在其中定义一个监视MatchCenter页面更改的方法。如果发生变化,我会调用UserMailer.matchcenter_notification(@user).deliver
。
我遇到问题的部分是什么放入MatchCenter控制器方法中,该方法将检测由外部源引起的页面更改。此外,如果有更好的方法来做到这一点,我很乐意听到它。所有相关代码如下。谢谢!
users_controller.rb:
class UsersController < ApplicationController
before_action :signed_in_user, only: [:edit, :update]
before_action :correct_user, only: [:edit, :update]
before_action :admin_user, only: [:index, :destroy]
def show
@user = User.find(params[:id])
@microposts = @user.microposts.paginate(page: params[:page])
end
def new
@user = User.new
end
def index
@users = User.paginate(page: params[:page])
end
def create
@user = User.new(user_params)
if @user.save
sign_in @user
flash[:success] = "Welcome to the MatchCenter Alpha Test!"
redirect_to root_path
else
render 'new'
end
end
def show
@user = User.find(params[:id])
end
def admin_user
redirect_to(root_url) unless current_user.admin?
end
def edit
@user = User.find(params[:id])
end
def destroy
User.find(params[:id]).destroy
flash[:success] = "User deleted."
redirect_to users_url
end
def update
@user = User.find(params[:id])
if @user.update_attributes(user_params)
flash[:success] = "Profile updated"
redirect_to @user
else
render 'edit'
end
end
private
def user_params
params.require(:user).permit(:name, :email, :password,
:password_confirmation)
end
# Before filters
def correct_user
@user = User.find(params[:id])
redirect_to(root_url) unless current_user?(@user)
end
end
microposts_controller.rb:
class MicropostsController < ApplicationController
before_action :signed_in_user
before_action :correct_user, only: :destroy
def new
@micropost = current_user.microposts.build
end
def create
@micropost = current_user.microposts.build(micropost_params)
if @micropost.save
flash[:success] = "Sweet! The item has been added to your watch list, and we'll notify you whenever matches are found."
redirect_to buy_path
else
render 'static_pages/home'
end
end
def destroy
@micropost.destroy
redirect_to buy_path
end
private
def micropost_params
params.require(:micropost).permit(:keyword, :min, :max, :condition)
end
def correct_user
@micropost = current_user.microposts.find_by(id: params[:id])
redirect_to root_url if @micropost.nil?
end
end
答案 0 :(得分:0)
如果MatchCenter
是在Ebay中检测到更改时被修改的模型,那么您可以使用观察者轻松实现此功能。
如果这是一个pre-rails-4应用程序,那么Observers就会被烘焙。对于rails 4,他们已经moved into a plugin。
创建观察者:
rails g observer MatchCenter
然后在新创建的观察者文件中,定义它正在观察的内容以及如何处理它:
class MatchCenterObserver < ActiveRecord::Observer
observe MatchCenter
def notify_users(match_center)
#
# Do any required notifications etc here
#
end
alias_method :after_create, :notify_users
alias_method :after_update, :notify_users
alias_method :after_destroy, :notify_users
end