我正在尝试创建一个邮件程序,只要用户注册就会发送一封邮件.很简单,但我是铁杆新手.
我有一个已经创建用户的网站.我有一个正常运行的登录和注册页面,但需要一些帮助来创建一个发送电子邮件确认链接的邮件程序,可能还有一个选项,可以在没有用户注册的情况下发送这些电子邮件,例如单独设置用户邀请页面.
我已经生成了一个模型邀请函.rb
class Invitation < ActiveRecord::Base
belongs_to :sender, :class_name => 'User'
has_one :recipient, :class_name => 'User'
validates_presence_of :recipient_email
validate :recipient_is_not_registered
validate :sender_has_invitations, :if => :sender
before_create :generate_token
before_create :decrement_sender_count, :if => :sender
private
def recipient_is_not_registered
errors.add :recipient_email, 'is already registered' if User.find_by_email(recipient_email)
end
def sender_has_invitations
unless sender.invitation_limit > 0
errors.add_to_base 'You have reached your limit of invitations to send.'
end
end
def generate_token
self.token = Digest::SHA1.hexdigest([Time.now, rand].join)
end
def decrement_sender_count
sender.decrement! :invitation_limit
end
#attr_accessible :sender_id, :recipient_email, :token, :sent_at
end
和我的invitiation_controller.rb
class InvitationsController < ApplicationController
def new
@invitation = Invitation.new
end
def create
@invitation = Invitation.new(params[:invitation])
@invitation.sender = current_user
if @invitation.save
if logged_in?
Mailer.deliver_invitation(@invitation, signup_url(@invitation.token))
flash[:notice] = "Thank you, invitation sent."
redirect_to projects_url
else
flash[:notice] = "Thank you, we will notify when we are ready."
redirect_to root_url
end
else
render :action => 'new'
end
end
end
我还需要编辑什么?如何将此连接到已经存在的用户注册和正常工作的登录?
最佳答案 您应该已经有一个UsersController或类似的东西用于注册目的,您当前通过signup_url命名路由访问.假设这条路线现在是这样的:
http://localhost:3000/register/code_here
您现在要做的就是检查控制器操作中的邀请并相应地处理它,如下所示:
def new
invite = Invite.find_by_token(params[:id]
if invite.nil?
redirect_to root_path, :notice => "Sorry, you need an invite to register"
end
@user = User.new(:email => invite.recipient_email)
end
def create
invite = Invite.find_by_token(params[:token]
if invite.nil?
redirect_to root_path, :notice => "Sorry, you need an invite to register"
end
begin
invite.nil.transaction do
invite.nil.destroy!
@user = User.create(params[:user)
end
redirect_to my_dashboard_path, :notice => "Yay!"
rescue ActiveRecord::RecordInvalid => invalid
render :new, :alert => "Validation errors"
end
end
如果没有邀请代码,您只需重定向到根页面即可.你可能想干一下这个检查.当有人使用邀请代码时,您可能希望从数据库中删除它.我把它包装在一个交易中,但这取决于你(创建用户可能更重要).
如果您想创建一个允许用户在不注册的情况下创建邀请的页面,那么就不要向InvitationsController添加身份验证并更新此代码段:
def create
@invitation = Invitation.new(params[:invitation])
@invitation.sender = current_user if logged_in?
if @invitation.save
Mailer.deliver_invitation(@invitation, signup_url(@invitation.token))
flash[:notice] = "Thank you, invitation sent."
if logged_in?
redirect_to projects_url
else
redirect_to root_url
end
else
render :action => 'new'
end
end
我不确定我是否覆盖了所有基础,但我认为这至少应该指向正确的方向.