我已经在我的RoR应用程序中设置了Action Mailer,我希望当用户的"MatchCenter“页面内容发生变化时,它会发送一封电子邮件给用户。
MatchCenter根据用户通过微博提供的标准,使用易趣的应用程序接口显示商品。这意味着结果会由于外部来源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
发布于 2014-01-15 07:15:47
如果MatchCenter
是一个在易趣中检测到变化时进行修改的模型,那么您可以使用观察者轻松地实现这一点。
如果这是一个rails-4之前的应用,那么观察者就会加入进来。在Rails4中,它们已经被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
https://stackoverflow.com/questions/21125171
复制相似问题